function EntityReferenceFieldTest::testEntityReferenceFieldValidation

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testEntityReferenceFieldValidation()
  2. 8.9.x 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 90

Class

EntityReferenceFieldTest
Tests for the entity reference field.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityReferenceFieldValidation() : void {
  // 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(sprintf('The referenced entity (%s: 9999) does not exist.', $this->referencedEntityType), $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(sprintf('This entity (%s: %s) cannot be referenced.', $this->referencedEntityType, $referenced_entity->id()), $violations[0]->getMessage());
}

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