function FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue

Same name in other branches
  1. 9 core/modules/field/tests/src/Kernel/FieldAttachStorageTest.php \Drupal\Tests\field\Kernel\FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue()
  2. 8.9.x core/modules/field/tests/src/Kernel/FieldAttachStorageTest.php \Drupal\Tests\field\Kernel\FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue()
  3. 11.x core/modules/field/tests/src/Kernel/FieldAttachStorageTest.php \Drupal\Tests\field\Kernel\FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue()

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

File

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

Class

FieldAttachStorageTest
Tests storage-related Field Attach API functions.

Namespace

Drupal\Tests\field\Kernel

Code

public function testFieldAttachSaveEmptyDataDefaultValue() : void {
    $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->assertEquals($default, $entity_init->{$this->fieldTestData->field_name}
        ->getValue(), '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->assertEquals($value, $entity->{$this->fieldTestData->field_name}
        ->getValue(), 'Prepopulated field value correctly maintained.');
}

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