function EntityDefinitionUpdateTest::testInitialValue

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityDefinitionUpdateTest.php \Drupal\KernelTests\Core\Entity\EntityDefinitionUpdateTest::testInitialValue()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityDefinitionUpdateTest.php \Drupal\KernelTests\Core\Entity\EntityDefinitionUpdateTest::testInitialValue()

Tests adding a base field with initial values.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityDefinitionUpdateTest.php, line 995

Class

EntityDefinitionUpdateTest
Tests EntityDefinitionUpdateManager functionality.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testInitialValue() : void {
  $storage = \Drupal::entityTypeManager()->getStorage('entity_test_update');
  $db_schema = $this->database
    ->schema();
  // Create two entities before adding the base field.
  /** @var \Drupal\entity_test\Entity\EntityTestUpdate $entity */
  $storage->create()
    ->save();
  $storage->create()
    ->save();
  // Add a base field with an initial value.
  $this->addBaseField();
  $storage_definition = BaseFieldDefinition::create('string')->setLabel(t('A new base field'))
    ->setInitialValue('test value');
  $this->assertFalse($db_schema->fieldExists('entity_test_update', 'new_base_field'), "New field 'new_base_field' does not exist before applying the update.");
  $this->entityDefinitionUpdateManager
    ->installFieldStorageDefinition('new_base_field', 'entity_test_update', 'entity_test', $storage_definition);
  $this->assertTrue($db_schema->fieldExists('entity_test_update', 'new_base_field'), "New field 'new_base_field' has been created on the 'entity_test_update' table.");
  // Check that the initial values have been applied.
  $storage = \Drupal::entityTypeManager()->getStorage('entity_test_update');
  $entities = $storage->loadMultiple();
  $this->assertEquals('test value', $entities[1]->get('new_base_field')->value);
  $this->assertEquals('test value', $entities[2]->get('new_base_field')->value);
}

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