function EntityFieldTest::testEntityConstraintValidation
Same name in other branches
- 9 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()
- 10 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()
- 11.x core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()
Tests validation constraints provided by the Entity API.
File
-
core/
tests/ Drupal/ KernelTests/ Core/ Entity/ EntityFieldTest.php, line 686
Class
- EntityFieldTest
- Tests the Entity Field API.
Namespace
Drupal\KernelTests\Core\EntityCode
public function testEntityConstraintValidation() {
$entity = $this->createTestEntity('entity_test');
$entity->save();
// Create a reference field item and let it reference the entity.
$definition = BaseFieldDefinition::create('entity_reference')->setLabel('Test entity')
->setSetting('target_type', 'entity_test');
$reference_field = \Drupal::typedDataManager()->create($definition);
$reference = $reference_field->appendItem([
'entity' => $entity,
])
->get('entity');
// Test validation the typed data object.
$violations = $reference->validate();
$this->assertEqual($violations->count(), 0);
// Test validating an entity of the wrong type.
$user = $this->createUser();
$user->save();
$node = $node = Node::create([
'type' => 'page',
'uid' => $user->id(),
'title' => $this->randomString(),
]);
$reference->setValue($node);
$violations = $reference->validate();
$this->assertEqual($violations->count(), 1);
// Test bundle validation.
NodeType::create([
'type' => 'article',
])->save();
$definition = BaseFieldDefinition::create('entity_reference')->setLabel('Test entity')
->setSetting('target_type', 'node')
->setSetting('handler_settings', [
'target_bundles' => [
'article' => 'article',
],
]);
$reference_field = \Drupal::TypedDataManager()->create($definition);
$reference_field->appendItem([
'entity' => $node,
]);
$violations = $reference_field->validate();
$this->assertEqual($violations->count(), 1);
$node = Node::create([
'type' => 'article',
'uid' => $user->id(),
'title' => $this->randomString(),
]);
$node->save();
$reference_field->entity = $node;
$violations = $reference_field->validate();
$this->assertEqual($violations->count(), 0);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.