function EntityReferenceFieldTest::testEntityReferenceFieldValidation

Same name in other branches
  1. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testEntityReferenceFieldValidation()
  2. 10 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testEntityReferenceFieldValidation()
  3. 11.x core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testEntityReferenceFieldValidation()

Tests reference field validation.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php, line 89

Class

EntityReferenceFieldTest
Tests for the entity reference field.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityReferenceFieldValidation() {
    // Test a valid reference.
    $referenced_entity = $this->container
        ->get('entity_type.manager')
        ->getStorage($this->referencedEntityType)
        ->create([
        'type' => $this->bundle,
    ]);
    $referenced_entity->save();
    $entity = $this->container
        ->get('entity_type.manager')
        ->getStorage($this->entityType)
        ->create([
        'type' => $this->bundle,
    ]);
    $entity->{$this->fieldName}->target_id = $referenced_entity->id();
    $violations = $entity->{$this->fieldName}
        ->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passes.');
    // Test an invalid reference.
    $entity->{$this->fieldName}->target_id = 9999;
    $violations = $entity->{$this->fieldName}
        ->validate();
    $this->assertEquals(1, $violations->count(), 'Validation throws a violation.');
    $this->assertEquals(t('The referenced entity (%type: %id) does not exist.', [
        '%type' => $this->referencedEntityType,
        '%id' => 9999,
    ]), $violations[0]->getMessage());
    // Test a non-referenceable bundle.
    entity_test_create_bundle('non_referenceable', NULL, $this->referencedEntityType);
    $referenced_entity = $this->entityTypeManager
        ->getStorage($this->referencedEntityType)
        ->create([
        'type' => 'non_referenceable',
    ]);
    $referenced_entity->save();
    $entity->{$this->fieldName}->target_id = $referenced_entity->id();
    $violations = $entity->{$this->fieldName}
        ->validate();
    $this->assertEquals(1, $violations->count(), 'Validation throws a violation.');
    $this->assertEquals(t('This entity (%type: %id) cannot be referenced.', [
        '%type' => $this->referencedEntityType,
        '%id' => $referenced_entity->id(),
    ]), $violations[0]->getMessage());
}

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