function SqlContentEntityStorageSchemaTest::testUpdateFieldStorageDefinitionThrowsException

Test to ensure that updating field with data triggers expected exceptions.

This test ensures that attempting to change the cardinality of a field with existing data triggers a expected exception.

File

core/tests/Drupal/KernelTests/Core/Entity/Sql/SqlContentEntityStorageSchemaTest.php, line 54

Class

SqlContentEntityStorageSchemaTest
Tests Sql Content Entity Storage Schema.

Namespace

Drupal\KernelTests\Core\Entity\Sql

Code

public function testUpdateFieldStorageDefinitionThrowsException() : void {
  // Install the test entity type with an additional field.
  // Don't care about the field type, just need a field with data.
  $field = BaseFieldDefinition::create('shape')->setName('shape')
    ->setProvider('entity_test');
  $this->state
    ->set('entity_test.additional_base_field_definitions', [
    'shape' => $field,
  ]);
  $this->entityDefinitionUpdateManager
    ->installFieldStorageDefinition('shape', 'entity_test', 'entity_test', $field);
  // Create an entity with field data.
  $entity = EntityTest::create([
    'user_id' => 2,
    'name' => $this->randomMachineName(),
    'shape' => [
      'shape' => 'rectangle',
      'color' => 'pink',
    ],
  ]);
  $entity->save();
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('user_id', 'entity_test');
  // Change the cardinality of the field storage definition.
  // This should throw an exception because the field has existing data.
  $field_storage_definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
  $this->expectException(FieldStorageDefinitionUpdateForbiddenException::class);
  $this->entityDefinitionUpdateManager
    ->updateFieldStorageDefinition($field_storage_definition);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.