function EntityReferenceFieldTest::testEntityReferenceFieldValidation
Same name in other branches
- 9 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testEntityReferenceFieldValidation()
- 10 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testEntityReferenceFieldValidation()
- 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\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->assertEqual($violations->count(), 0, 'Validation passes.');
// Test an invalid reference.
$entity->{$this->fieldName}->target_id = 9999;
$violations = $entity->{$this->fieldName}
->validate();
$this->assertEqual($violations->count(), 1, 'Validation throws a violation.');
$this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%type: %id) does not exist.', [
'%type' => $this->referencedEntityType,
'%id' => 9999,
]));
// 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->assertEqual($violations->count(), 1, 'Validation throws a violation.');
$this->assertEqual($violations[0]->getMessage(), t('This entity (%type: %id) cannot be referenced.', [
'%type' => $this->referencedEntityType,
'%id' => $referenced_entity->id(),
]));
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.