public function EntityReferenceFieldTest::testEntityReferenceFieldValidation in Drupal 9
Same name and namespace in other branches
- 8 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\EntityCode
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());
}