function FieldStorageCrudTest::testUpdate

Same name in other branches
  1. 8.9.x 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()
  3. 11.x core/modules/field/tests/src/Kernel/FieldStorageCrudTest.php \Drupal\Tests\field\Kernel\FieldStorageCrudTest::testUpdate()

Tests updating a field storage.

File

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

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->assertCount($field_storage->getCardinality(), $entity->field_update);
        // Now check the values themselves.
        for ($delta = 0; $delta < $cardinality; $delta++) {
            $this->assertEquals($delta + 1, $entity->field_update[$delta]->value);
        }
        // Increase $cardinality and set the field cardinality to the new value.
        $field_storage->setCardinality(++$cardinality);
        $field_storage->save();
    } while ($cardinality < 6);
}

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