You are here

public function FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/field/tests/src/Kernel/FieldAttachStorageTest.php \Drupal\Tests\field\Kernel\FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue()

Test insert with empty or NULL fields, with default value.

File

core/modules/field/tests/src/Kernel/FieldAttachStorageTest.php, line 196

Class

FieldAttachStorageTest
Tests storage-related Field Attach API functions.

Namespace

Drupal\Tests\field\Kernel

Code

public function testFieldAttachSaveEmptyDataDefaultValue() {
  $entity_type = 'entity_test_rev';
  $this
    ->createFieldWithStorage('', $entity_type);

  // Add a default value function.
  $this->fieldTestData->field
    ->set('default_value_callback', 'field_test_default_value');
  $this->fieldTestData->field
    ->save();

  // Verify that fields are populated with default values.
  $entity_init = $this->container
    ->get('entity_type.manager')
    ->getStorage($entity_type)
    ->create([
    'id' => 1,
    'revision_id' => 1,
  ]);
  $default = field_test_default_value($entity_init, $this->fieldTestData->field);
  $this
    ->assertEqual($entity_init->{$this->fieldTestData->field_name}
    ->getValue(), $default, 'Default field value correctly populated.');

  // Insert: Field is NULL.
  $entity = clone $entity_init;
  $entity->{$this->fieldTestData->field_name} = NULL;
  $entity
    ->enforceIsNew();
  $entity = $this
    ->entitySaveReload($entity);
  $this
    ->assertTrue($entity->{$this->fieldTestData->field_name}
    ->isEmpty(), 'Insert: NULL field results in no value saved');

  // Verify that prepopulated field values are not overwritten by defaults.
  $value = [
    [
      'value' => $default[0]['value'] - mt_rand(1, 127),
    ],
  ];
  $entity = $this->container
    ->get('entity_type.manager')
    ->getStorage($entity_type)
    ->create([
    'type' => $entity_init
      ->bundle(),
    $this->fieldTestData->field_name => $value,
  ]);
  $this
    ->assertEqual($entity->{$this->fieldTestData->field_name}
    ->getValue(), $value, 'Prepopulated field value correctly maintained.');
}