function FieldValidationTest::testCardinalityConstraint

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

Tests that the number of values is validated against the field cardinality.

File

core/modules/field/tests/src/Kernel/FieldValidationTest.php, line 50

Class

FieldValidationTest
Tests field validation.

Namespace

Drupal\Tests\field\Kernel

Code

public function testCardinalityConstraint() : void {
    $cardinality = $this->fieldTestData->field_storage
        ->getCardinality();
    $entity = $this->entity;
    for ($delta = 0; $delta < $cardinality + 1; $delta++) {
        $entity->{$this->fieldTestData->field_name}[] = [
            'value' => 1,
        ];
    }
    // Validate the field.
    $violations = $entity->{$this->fieldTestData->field_name}
        ->validate();
    // Check that the expected constraint violations are reported.
    $this->assertCount(1, $violations);
    $this->assertEquals('', $violations[0]->getPropertyPath());
    $this->assertEquals(sprintf('%s: this field cannot hold more than %s values.', $this->fieldTestData->field
        ->getLabel(), $cardinality), $violations[0]->getMessage());
}

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