function EntityReferenceFieldTest::testReferencedEntitiesStringId
Same name in other branches
- 9 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testReferencedEntitiesStringId()
- 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testReferencedEntitiesStringId()
- 10 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testReferencedEntitiesStringId()
Tests referencing entities with string IDs.
File
-
core/
tests/ Drupal/ KernelTests/ Core/ Entity/ EntityReferenceFieldTest.php, line 197
Class
- EntityReferenceFieldTest
- Tests for the entity reference field.
Namespace
Drupal\KernelTests\Core\EntityCode
public function testReferencedEntitiesStringId() : void {
$field_name = 'entity_reference_string_id';
$this->installEntitySchema('entity_test_string_id');
$this->createEntityReferenceField($this->entityType, $this->bundle, $field_name, 'Field test', 'entity_test_string_id', 'default', [
'target_bundles' => [
$this->bundle,
],
], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
// Create the parent entity.
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
// Create the default target entity.
$target_entity = EntityTestStringId::create([
'id' => $this->randomString(),
'type' => $this->bundle,
]);
$target_entity->save();
// Set the field value.
$entity->{$field_name}
->setValue([
[
'target_id' => $target_entity->id(),
],
]);
// Load the target entities using EntityReferenceField::referencedEntities().
$entities = $entity->{$field_name}
->referencedEntities();
$this->assertEquals($target_entity->id(), $entities[0]->id());
// Test that a string ID works as a default value and the field's config
// schema is correct.
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $field_name);
$field->setDefaultValue($target_entity->id());
$field->save();
$this->assertConfigSchema(\Drupal::service('config.typed'), 'field.field.' . $field->id(), $field->toArray());
// Test that the default value works.
$entity = $this->container
->get('entity_type.manager')
->getStorage($this->entityType)
->create([
'type' => $this->bundle,
]);
$entities = $entity->{$field_name}
->referencedEntities();
$this->assertEquals($target_entity->id(), $entities[0]->id());
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.