You are here

function FieldAttachStorageTest::testFieldAttachSaveEmptyData 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::testFieldAttachSaveEmptyData()

Tests insert and update with empty or NULL fields.

File

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

Class

FieldAttachStorageTest
Tests storage-related Field Attach API functions.

Namespace

Drupal\field\Tests

Code

function testFieldAttachSaveEmptyData() {
  $entity_type = 'entity_test';
  $this
    ->createFieldWithStorage('', $entity_type);
  $entity_init = entity_create($entity_type, array(
    'id' => 1,
  ));

  // 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');

  // All saves after this point should be updates, not inserts.
  $entity_init
    ->enforceIsNew(FALSE);

  // Add some real data.
  $entity = clone $entity_init;
  $values = $this
    ->_generateTestFieldValues(1);
  $entity->{$this->fieldTestData->field_name} = $values;
  $entity = $this
    ->entitySaveReload($entity);
  $this
    ->assertEqual($entity->{$this->fieldTestData->field_name}
    ->getValue(), $values, 'Field data saved');

  // Update: Field is NULL. Data should be wiped.
  $entity = clone $entity_init;
  $entity->{$this->fieldTestData->field_name} = NULL;
  $entity = $this
    ->entitySaveReload($entity);
  $this
    ->assertTrue($entity->{$this->fieldTestData->field_name}
    ->isEmpty(), 'Update: NULL field removes existing values');

  // Re-add some data.
  $entity = clone $entity_init;
  $values = $this
    ->_generateTestFieldValues(1);
  $entity->{$this->fieldTestData->field_name} = $values;
  $entity = $this
    ->entitySaveReload($entity);
  $this
    ->assertEqual($entity->{$this->fieldTestData->field_name}
    ->getValue(), $values, 'Field data saved');

  // Update: Field is empty array. Data should be wiped.
  $entity = clone $entity_init;
  $entity->{$this->fieldTestData->field_name} = array();
  $entity = $this
    ->entitySaveReload($entity);
  $this
    ->assertTrue($entity->{$this->fieldTestData->field_name}
    ->isEmpty(), 'Update: empty array removes existing values');
}