You are here

function FieldAttachStorageTest::testFieldAttachSaveEmptyDataDefaultValue in Zircon Profile 8

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

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

File

core/modules/field/src/Tests/FieldAttachStorageTest.php, line 193
Contains \Drupal\field\Tests\FieldAttachStorageTest.

Class

FieldAttachStorageTest
Tests storage-related Field Attach API functions.

Namespace

Drupal\field\Tests

Code

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 = entity_create($entity_type, array(
    '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 = array(
    array(
      'value' => $default[0]['value'] - mt_rand(1, 127),
    ),
  );
  $entity = entity_create($entity_type, array(
    'type' => $entity_init
      ->bundle(),
    $this->fieldTestData->field_name => $value,
  ));
  $this
    ->assertEqual($entity->{$this->fieldTestData->field_name}
    ->getValue(), $value, 'Prepopulated field value correctly maintained.');
}