function UniqueValuesConstraintValidatorTest::testValidationOwn

Same name in other branches
  1. 10 core/tests/Drupal/KernelTests/Core/Validation/UniqueValuesConstraintValidatorTest.php \Drupal\KernelTests\Core\Validation\UniqueValuesConstraintValidatorTest::testValidationOwn()

Tests the UniqueField validation constraint validator for existing value in the same entity.

Case 3. Try to add existing value for unique field in the same entity.

@covers ::validate

Throws

\Drupal\Core\Entity\EntityStorageException

File

core/tests/Drupal/KernelTests/Core/Validation/UniqueValuesConstraintValidatorTest.php, line 193

Class

UniqueValuesConstraintValidatorTest
Tests the unique field value validation constraint.

Namespace

Drupal\KernelTests\Core\Validation

Code

public function testValidationOwn() : void {
    // Create new entity with two identical values for the testing field.
    $definition = [
        'user_id' => 0,
        'field_test_text' => [
            'text0',
            'text0',
        ],
    ];
    $entity = EntityTestUniqueConstraint::create($definition);
    $violations = $entity->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('field_test_text.1', $violations[0]->getPropertyPath());
    $this->assertEquals(sprintf('A unique field entity with unique_field_test %s already exists.', $definition['field_test_text'][1]), $violations[0]->getMessage());
    // Create entity with two different values for the testing field.
    $definition = [
        'user_id' => 0,
        'field_test_text' => [
            'text1',
            'text2',
        ],
    ];
    $entity = EntityTestUniqueConstraint::create($definition);
    $violations = $entity->validate();
    $this->assertCount(0, $violations);
    $entity->save();
    $violations = $entity->validate();
    $this->assertCount(0, $violations);
    // Add existing value.
    $entity->get('field_test_text')
        ->appendItem($definition['field_test_text'][0]);
    $violations = $entity->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('field_test_text.2', $violations[0]->getPropertyPath());
    $this->assertEquals(sprintf('A unique field entity with unique_field_test %s already exists.', $definition['field_test_text'][0]), $violations[0]->getMessage());
}

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