3 namespace Drupal\Tests\field\Kernel;
6 * Tests field validation.
10 class FieldValidationTest extends FieldKernelTestBase {
23 * @var \Drupal\Core\Entity\EntityInterface
27 protected function setUp() {
30 // Create a field and storage of type 'test_field', on the 'entity_test'
32 $this->entityType = 'entity_test';
33 $this->bundle = 'entity_test';
34 $this->createFieldWithStorage('', $this->entityType, $this->bundle);
36 // Create an 'entity_test' entity.
37 $this->entity = entity_create($this->entityType, [
38 'type' => $this->bundle,
43 * Tests that the number of values is validated against the field cardinality.
45 public function testCardinalityConstraint() {
46 $cardinality = $this->fieldTestData->field_storage->getCardinality();
47 $entity = $this->entity;
49 for ($delta = 0; $delta < $cardinality + 1; $delta++) {
50 $entity->{$this->fieldTestData->field_name}[] = ['value' => 1];
53 // Validate the field.
54 $violations = $entity->{$this->fieldTestData->field_name}->validate();
56 // Check that the expected constraint violations are reported.
57 $this->assertEqual(count($violations), 1);
58 $this->assertEqual($violations[0]->getPropertyPath(), '');
59 $this->assertEqual($violations[0]->getMessage(), t('%name: this field cannot hold more than @count values.', ['%name' => $this->fieldTestData->field->getLabel(), '@count' => $cardinality]));
63 * Tests that constraints defined by the field type are validated.
65 public function testFieldConstraints() {
66 $cardinality = $this->fieldTestData->field_storage->getCardinality();
67 $entity = $this->entity;
69 // The test is only valid if the field cardinality is greater than 2.
70 $this->assertTrue($cardinality >= 2);
72 // Set up values for the field.
73 $expected_violations = [];
74 for ($delta = 0; $delta < $cardinality; $delta++) {
75 // All deltas except '1' have incorrect values.
81 $expected_violations[$delta . '.value'][] = t('%name does not accept the value -1.', ['%name' => $this->fieldTestData->field->getLabel()]);
83 $entity->{$this->fieldTestData->field_name}[] = $value;
86 // Validate the field.
87 $violations = $entity->{$this->fieldTestData->field_name}->validate();
89 // Check that the expected constraint violations are reported.
90 $violations_by_path = [];
91 foreach ($violations as $violation) {
92 $violations_by_path[$violation->getPropertyPath()][] = $violation->getMessage();
94 $this->assertEqual($violations_by_path, $expected_violations);