3 namespace Drupal\Core\Entity\Plugin\DataType;
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\TypedData\DataReferenceBase;
9 * Defines an 'entity_reference' data type.
11 * This serves as 'entity' property of entity reference field items and gets
12 * its value set from the parent, i.e. LanguageItem.
14 * The plain value of this reference is the entity object, i.e. an instance of
15 * \Drupal\Core\Entity\EntityInterface. For setting the value the entity object
16 * or the entity ID may be passed.
18 * Note that the definition of the referenced entity's type is required, whereas
19 * defining referenceable entity bundle(s) is optional. A reference defining the
20 * type and bundle of the referenced entity can be created as following:
22 * $definition = \Drupal\Core\Entity\EntityDefinition::create($entity_type)
23 * ->addConstraint('Bundle', $bundle);
24 * \Drupal\Core\TypedData\DataReferenceDefinition::create('entity')
25 * ->setTargetDefinition($definition);
29 * id = "entity_reference",
30 * label = @Translation("Entity reference"),
31 * definition_class = "\Drupal\Core\TypedData\DataReferenceDefinition"
34 class EntityReference extends DataReferenceBase {
44 * Gets the definition of the referenced entity.
46 * @return \Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface
47 * The reference target's definition.
49 public function getTargetDefinition() {
50 return $this->definition->getTargetDefinition();
54 * Checks whether the target entity has not been saved yet.
57 * TRUE if the entity is new, FALSE otherwise.
59 public function isTargetNew() {
60 // If only an ID is given, the reference cannot be a new entity.
61 return !isset($this->id) && isset($this->target) && $this->target->getValue()->isNew();
67 public function getTarget() {
68 if (!isset($this->target) && isset($this->id)) {
69 // If we have a valid reference, return the entity's TypedData adapter.
70 $entity = \Drupal::entityTypeManager()
71 ->getStorage($this->getTargetDefinition()->getEntityTypeId())
73 $this->target = isset($entity) ? $entity->getTypedData() : NULL;
81 public function getTargetIdentifier() {
82 if (isset($this->id)) {
85 elseif ($entity = $this->getValue()) {
93 public function setValue($value, $notify = TRUE) {
97 // Both the entity ID and the entity object may be passed as value. The
98 // reference may also be unset by passing NULL as value.
100 $this->target = NULL;
102 elseif ($value instanceof EntityInterface) {
103 $this->target = $value->getTypedData();
105 elseif (!is_scalar($value) || $this->getTargetDefinition()->getEntityTypeId() === NULL) {
106 throw new \InvalidArgumentException('Value is not a valid entity.');
111 // Notify the parent of any changes.
112 if ($notify && isset($this->parent)) {
113 $this->parent->onChange($this->name);
120 public function getString() {
121 if ($entity = $this->getValue()) {
122 return $entity->label();