function FieldValidationTest::testFieldConstraints

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

Tests that constraints defined by the field type are validated.

File

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

Class

FieldValidationTest
Tests field validation.

Namespace

Drupal\Tests\field\Kernel

Code

public function testFieldConstraints() : void {
    $cardinality = $this->fieldTestData->field_storage
        ->getCardinality();
    $entity = $this->entity;
    // The test is only valid if the field cardinality is greater than 1.
    $this->assertGreaterThan(1, $cardinality);
    // Set up values for the field.
    $expected_violations = [];
    for ($delta = 0; $delta < $cardinality; $delta++) {
        // All deltas except '1' have incorrect values.
        if ($delta == 1) {
            $value = 1;
        }
        else {
            $value = -1;
            $expected_violations[$delta . '.value'][] = t('%name does not accept the value -1.', [
                '%name' => $this->fieldTestData->field
                    ->getLabel(),
            ]);
        }
        $entity->{$this->fieldTestData->field_name}[] = $value;
    }
    // Validate the field.
    $violations = $entity->{$this->fieldTestData->field_name}
        ->validate();
    // Check that the expected constraint violations are reported.
    $violations_by_path = [];
    foreach ($violations as $violation) {
        $violations_by_path[$violation->getPropertyPath()][] = $violation->getMessage();
    }
    $this->assertEquals($expected_violations, $violations_by_path);
}

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