You are here

public function FieldStorageCrudTest::testUpdate in Drupal 8

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

Test updating a field storage.

File

core/modules/field/tests/src/Kernel/FieldStorageCrudTest.php, line 427

Class

FieldStorageCrudTest
Tests field storage create, read, update, and delete.

Namespace

Drupal\Tests\field\Kernel

Code

public function testUpdate() {

  // Create a field with a defined cardinality, so that we can ensure it's
  // respected. Since cardinality enforcement is consistent across database
  // systems, it makes a good test case.
  $cardinality = 4;
  $field_storage = FieldStorageConfig::create([
    'field_name' => 'field_update',
    'entity_type' => 'entity_test',
    'type' => 'test_field',
    'cardinality' => $cardinality,
  ]);
  $field_storage
    ->save();
  $field = FieldConfig::create([
    'field_storage' => $field_storage,
    'entity_type' => 'entity_test',
    'bundle' => 'entity_test',
  ]);
  $field
    ->save();
  do {
    $entity = EntityTest::create();

    // Fill in the entity with more values than $cardinality.
    for ($i = 0; $i < 20; $i++) {

      // We can not use $i here because 0 values are filtered out.
      $entity->field_update[] = $i + 1;
    }

    // Load back and assert there are $cardinality number of values.
    $entity = $this
      ->entitySaveReload($entity);
    $this
      ->assertEqual(count($entity->field_update), $field_storage
      ->getCardinality());

    // Now check the values themselves.
    for ($delta = 0; $delta < $cardinality; $delta++) {
      $this
        ->assertEqual($entity->field_update[$delta]->value, $delta + 1);
    }

    // Increase $cardinality and set the field cardinality to the new value.
    $field_storage
      ->setCardinality(++$cardinality);
    $field_storage
      ->save();
  } while ($cardinality < 6);
}