3 namespace Drupal\Core\Field\Plugin\Field\FieldType;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\NestedArray;
7 use Drupal\Core\Entity\EntityInterface;
8 use Drupal\Core\Entity\EntityTypeInterface;
9 use Drupal\Core\Entity\FieldableEntityInterface;
10 use Drupal\Core\Entity\TypedData\EntityDataDefinition;
11 use Drupal\Core\Field\FieldDefinitionInterface;
12 use Drupal\Core\Field\FieldItemBase;
13 use Drupal\Core\Field\FieldStorageDefinitionInterface;
14 use Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface;
15 use Drupal\Core\Form\FormStateInterface;
16 use Drupal\Core\Form\OptGroup;
17 use Drupal\Core\Render\Element;
18 use Drupal\Core\Session\AccountInterface;
19 use Drupal\Core\StringTranslation\TranslatableMarkup;
20 use Drupal\Core\TypedData\DataReferenceDefinition;
21 use Drupal\Core\TypedData\DataReferenceTargetDefinition;
22 use Drupal\Core\TypedData\OptionsProviderInterface;
23 use Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraint;
26 * Defines the 'entity_reference' entity field type.
28 * Supported settings (below the definition's 'settings' key) are:
29 * - target_type: The entity type to reference. Required.
32 * id = "entity_reference",
33 * label = @Translation("Entity reference"),
34 * description = @Translation("An entity field containing an entity reference."),
35 * category = @Translation("Reference"),
36 * default_widget = "entity_reference_autocomplete",
37 * default_formatter = "entity_reference_label",
38 * list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
41 class EntityReferenceItem extends FieldItemBase implements OptionsProviderInterface, PreconfiguredFieldUiOptionsInterface {
46 public static function defaultStorageSettings() {
48 'target_type' => \Drupal::moduleHandler()->moduleExists('node') ? 'node' : 'user',
49 ] + parent::defaultStorageSettings();
55 public static function defaultFieldSettings() {
57 'handler' => 'default',
58 'handler_settings' => [],
59 ] + parent::defaultFieldSettings();
65 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
66 $settings = $field_definition->getSettings();
67 $target_type_info = \Drupal::entityManager()->getDefinition($settings['target_type']);
69 $target_id_data_type = 'string';
70 if ($target_type_info->entityClassImplements(FieldableEntityInterface::class)) {
71 $id_definition = \Drupal::entityManager()->getBaseFieldDefinitions($settings['target_type'])[$target_type_info->getKey('id')];
72 if ($id_definition->getType() === 'integer') {
73 $target_id_data_type = 'integer';
77 if ($target_id_data_type === 'integer') {
78 $target_id_definition = DataReferenceTargetDefinition::create('integer')
79 ->setLabel(new TranslatableMarkup('@label ID', ['@label' => $target_type_info->getLabel()]))
80 ->setSetting('unsigned', TRUE);
83 $target_id_definition = DataReferenceTargetDefinition::create('string')
84 ->setLabel(new TranslatableMarkup('@label ID', ['@label' => $target_type_info->getLabel()]));
86 $target_id_definition->setRequired(TRUE);
87 $properties['target_id'] = $target_id_definition;
89 $properties['entity'] = DataReferenceDefinition::create('entity')
90 ->setLabel($target_type_info->getLabel())
91 ->setDescription(new TranslatableMarkup('The referenced entity'))
92 // The entity object is computed out of the entity ID.
95 ->setTargetDefinition(EntityDataDefinition::create($settings['target_type']))
96 // We can add a constraint for the target entity type. The list of
97 // referenceable bundles is a field setting, so the corresponding
98 // constraint is added dynamically in ::getConstraints().
99 ->addConstraint('EntityType', $settings['target_type']);
107 public static function mainPropertyName() {
114 public static function schema(FieldStorageDefinitionInterface $field_definition) {
115 $target_type = $field_definition->getSetting('target_type');
116 $target_type_info = \Drupal::entityManager()->getDefinition($target_type);
117 $properties = static::propertyDefinitions($field_definition)['target_id'];
118 if ($target_type_info->entityClassImplements(FieldableEntityInterface::class) && $properties->getDataType() === 'integer') {
121 'description' => 'The ID of the target entity.',
130 'description' => 'The ID of the target entity.',
131 'type' => 'varchar_ascii',
132 // If the target entities act as bundles for another entity type,
133 // their IDs should not exceed the maximum length for bundles.
134 'length' => $target_type_info->getBundleOf() ? EntityTypeInterface::BUNDLE_MAX_LENGTH : 255,
140 'columns' => $columns,
142 'target_id' => ['target_id'],
152 public function getConstraints() {
153 $constraints = parent::getConstraints();
154 // Remove the 'AllowedValuesConstraint' validation constraint because entity
155 // reference fields already use the 'ValidReference' constraint.
156 foreach ($constraints as $key => $constraint) {
157 if ($constraint instanceof AllowedValuesConstraint) {
158 unset($constraints[$key]);
167 public function setValue($values, $notify = TRUE) {
168 if (isset($values) && !is_array($values)) {
169 // If either a scalar or an object was passed as the value for the item,
170 // assign it to the 'entity' property since that works for both cases.
171 $this->set('entity', $values, $notify);
174 parent::setValue($values, FALSE);
175 // Support setting the field item with only one property, but make sure
176 // values stay in sync if only property is passed.
177 // NULL is a valid value, so we use array_key_exists().
178 if (is_array($values) && array_key_exists('target_id', $values) && !isset($values['entity'])) {
179 $this->onChange('target_id', FALSE);
181 elseif (is_array($values) && !array_key_exists('target_id', $values) && isset($values['entity'])) {
182 $this->onChange('entity', FALSE);
184 elseif (is_array($values) && array_key_exists('target_id', $values) && isset($values['entity'])) {
185 // If both properties are passed, verify the passed values match. The
186 // only exception we allow is when we have a new entity: in this case
187 // its actual id and target_id will be different, due to the new entity
189 $entity_id = $this->get('entity')->getTargetIdentifier();
190 // If the entity has been saved and we're trying to set both the
191 // target_id and the entity values with a non-null target ID, then the
192 // value for target_id should match the ID of the entity value. The
193 // entity ID as returned by $entity->id() might be a string, but the
194 // provided target_id might be an integer - therefore we have to do a
195 // non-strict comparison.
196 if (!$this->entity->isNew() && $values['target_id'] !== NULL && ($entity_id != $values['target_id'])) {
197 throw new \InvalidArgumentException('The target id and entity passed to the entity reference item do not match.');
200 // Notify the parent if necessary.
201 if ($notify && $this->parent) {
202 $this->parent->onChange($this->getName());
211 public function getValue() {
212 $values = parent::getValue();
214 // If there is an unsaved entity, return it as part of the field item values
215 // to ensure idempotency of getValue() / setValue().
216 if ($this->hasNewEntity()) {
217 $values['entity'] = $this->entity;
225 public function onChange($property_name, $notify = TRUE) {
226 // Make sure that the target ID and the target property stay in sync.
227 if ($property_name == 'entity') {
228 $property = $this->get('entity');
229 $target_id = $property->isTargetNew() ? NULL : $property->getTargetIdentifier();
230 $this->writePropertyValue('target_id', $target_id);
232 elseif ($property_name == 'target_id') {
233 $this->writePropertyValue('entity', $this->target_id);
235 parent::onChange($property_name, $notify);
241 public function isEmpty() {
242 // Avoid loading the entity by first checking the 'target_id'.
243 if ($this->target_id !== NULL) {
246 if ($this->entity && $this->entity instanceof EntityInterface) {
255 public function preSave() {
256 if ($this->hasNewEntity()) {
257 // Save the entity if it has not already been saved by some other code.
258 if ($this->entity->isNew()) {
259 $this->entity->save();
261 // Make sure the parent knows we are updating this property so it can
263 $this->target_id = $this->entity->id();
265 if (!$this->isEmpty() && $this->target_id === NULL) {
266 $this->target_id = $this->entity->id();
273 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
274 $manager = \Drupal::service('plugin.manager.entity_reference_selection');
276 // Instead of calling $manager->getSelectionHandler($field_definition)
277 // replicate the behavior to be able to override the sorting settings.
279 'target_type' => $field_definition->getFieldStorageDefinition()->getSetting('target_type'),
280 'handler' => $field_definition->getSetting('handler'),
281 'handler_settings' => $field_definition->getSetting('handler_settings') ?: [],
285 $entity_type = \Drupal::entityManager()->getDefinition($options['target_type']);
286 $options['handler_settings']['sort'] = [
287 'field' => $entity_type->getKey('id'),
288 'direction' => 'DESC',
290 $selection_handler = $manager->getInstance($options);
292 // Select a random number of references between the last 50 referenceable
294 if ($referenceable = $selection_handler->getReferenceableEntities(NULL, 'CONTAINS', 50)) {
295 $group = array_rand($referenceable);
296 $values['target_id'] = array_rand($referenceable[$group]);
304 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
305 $element['target_type'] = [
307 '#title' => t('Type of item to reference'),
308 '#options' => \Drupal::entityManager()->getEntityTypeLabels(TRUE),
309 '#default_value' => $this->getSetting('target_type'),
311 '#disabled' => $has_data,
321 public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
322 $field = $form_state->getFormObject()->getEntity();
324 // Get all selection plugins for this entity type.
325 $selection_plugins = \Drupal::service('plugin.manager.entity_reference_selection')->getSelectionGroups($this->getSetting('target_type'));
326 $handlers_options = [];
327 foreach (array_keys($selection_plugins) as $selection_group_id) {
328 // We only display base plugins (e.g. 'default', 'views', ...) and not
329 // entity type specific plugins (e.g. 'default:node', 'default:user',
331 if (array_key_exists($selection_group_id, $selection_plugins[$selection_group_id])) {
332 $handlers_options[$selection_group_id] = Html::escape($selection_plugins[$selection_group_id][$selection_group_id]['label']);
334 elseif (array_key_exists($selection_group_id . ':' . $this->getSetting('target_type'), $selection_plugins[$selection_group_id])) {
335 $selection_group_plugin = $selection_group_id . ':' . $this->getSetting('target_type');
336 $handlers_options[$selection_group_plugin] = Html::escape($selection_plugins[$selection_group_id][$selection_group_plugin]['base_plugin_label']);
341 '#type' => 'container',
342 '#process' => [[get_class($this), 'fieldSettingsAjaxProcess']],
343 '#element_validate' => [[get_class($this), 'fieldSettingsFormValidate']],
347 '#type' => 'details',
348 '#title' => t('Reference type'),
351 '#process' => [[get_class($this), 'formProcessMergeParent']],
354 $form['handler']['handler'] = [
356 '#title' => t('Reference method'),
357 '#options' => $handlers_options,
358 '#default_value' => $field->getSetting('handler'),
361 '#limit_validation_errors' => [],
363 $form['handler']['handler_submit'] = [
365 '#value' => t('Change handler'),
366 '#limit_validation_errors' => [],
368 'class' => ['js-hide'],
370 '#submit' => [[get_class($this), 'settingsAjaxSubmit']],
373 $form['handler']['handler_settings'] = [
374 '#type' => 'container',
375 '#attributes' => ['class' => ['entity_reference-settings']],
378 $handler = \Drupal::service('plugin.manager.entity_reference_selection')->getSelectionHandler($field);
379 $form['handler']['handler_settings'] += $handler->buildConfigurationForm([], $form_state);
385 * Form element validation handler; Invokes selection plugin's validation.
388 * The form where the settings form is being included in.
389 * @param \Drupal\Core\Form\FormStateInterface $form_state
390 * The form state of the (entire) configuration form.
392 public static function fieldSettingsFormValidate(array $form, FormStateInterface $form_state) {
393 $field = $form_state->getFormObject()->getEntity();
394 $handler = \Drupal::service('plugin.manager.entity_reference_selection')->getSelectionHandler($field);
395 $handler->validateConfigurationForm($form, $form_state);
399 * Determines whether the item holds an unsaved entity.
401 * This is notably used for "autocreate" widgets, and more generally to
402 * support referencing freshly created entities (they will get saved
403 * automatically as the hosting entity gets saved).
406 * TRUE if the item holds an unsaved entity.
408 public function hasNewEntity() {
409 return !$this->isEmpty() && $this->target_id === NULL && $this->entity->isNew();
415 public static function calculateDependencies(FieldDefinitionInterface $field_definition) {
416 $dependencies = parent::calculateDependencies($field_definition);
417 $manager = \Drupal::entityManager();
418 $target_entity_type = $manager->getDefinition($field_definition->getFieldStorageDefinition()->getSetting('target_type'));
420 // Depend on default values entity types configurations.
421 if ($default_value = $field_definition->getDefaultValueLiteral()) {
422 foreach ($default_value as $value) {
423 if (is_array($value) && isset($value['target_uuid'])) {
424 $entity = \Drupal::entityManager()->loadEntityByUuid($target_entity_type->id(), $value['target_uuid']);
425 // If the entity does not exist do not create the dependency.
426 // @see \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()
428 $dependencies[$target_entity_type->getConfigDependencyKey()][] = $entity->getConfigDependencyName();
434 // Depend on target bundle configurations. Dependencies for 'target_bundles'
435 // also covers the 'auto_create_bundle' setting, if any, because its value
436 // is included in the 'target_bundles' list.
437 $handler = $field_definition->getSetting('handler_settings');
438 if (!empty($handler['target_bundles'])) {
439 if ($bundle_entity_type_id = $target_entity_type->getBundleEntityType()) {
440 if ($storage = $manager->getStorage($bundle_entity_type_id)) {
441 foreach ($storage->loadMultiple($handler['target_bundles']) as $bundle) {
442 $dependencies[$bundle->getConfigDependencyKey()][] = $bundle->getConfigDependencyName();
448 return $dependencies;
454 public static function calculateStorageDependencies(FieldStorageDefinitionInterface $field_definition) {
455 $dependencies = parent::calculateStorageDependencies($field_definition);
456 $target_entity_type = \Drupal::entityManager()->getDefinition($field_definition->getSetting('target_type'));
457 $dependencies['module'][] = $target_entity_type->getProvider();
458 return $dependencies;
464 public static function onDependencyRemoval(FieldDefinitionInterface $field_definition, array $dependencies) {
465 $changed = parent::onDependencyRemoval($field_definition, $dependencies);
466 $entity_manager = \Drupal::entityManager();
467 $target_entity_type = $entity_manager->getDefinition($field_definition->getFieldStorageDefinition()->getSetting('target_type'));
469 // Try to update the default value config dependency, if possible.
470 if ($default_value = $field_definition->getDefaultValueLiteral()) {
471 foreach ($default_value as $key => $value) {
472 if (is_array($value) && isset($value['target_uuid'])) {
473 $entity = $entity_manager->loadEntityByUuid($target_entity_type->id(), $value['target_uuid']);
474 // @see \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()
475 if ($entity && isset($dependencies[$entity->getConfigDependencyKey()][$entity->getConfigDependencyName()])) {
476 unset($default_value[$key]);
482 $field_definition->setDefaultValue($default_value);
486 // Update the 'target_bundles' handler setting if a bundle config dependency
488 $bundles_changed = FALSE;
489 $handler_settings = $field_definition->getSetting('handler_settings');
490 if (!empty($handler_settings['target_bundles'])) {
491 if ($bundle_entity_type_id = $target_entity_type->getBundleEntityType()) {
492 if ($storage = $entity_manager->getStorage($bundle_entity_type_id)) {
493 foreach ($storage->loadMultiple($handler_settings['target_bundles']) as $bundle) {
494 if (isset($dependencies[$bundle->getConfigDependencyKey()][$bundle->getConfigDependencyName()])) {
495 unset($handler_settings['target_bundles'][$bundle->id()]);
497 // If this bundle is also used in the 'auto_create_bundle'
498 // setting, disable the auto-creation feature completely.
499 $auto_create_bundle = !empty($handler_settings['auto_create_bundle']) ? $handler_settings['auto_create_bundle'] : FALSE;
500 if ($auto_create_bundle && $auto_create_bundle == $bundle->id()) {
501 $handler_settings['auto_create'] = NULL;
502 $handler_settings['auto_create_bundle'] = NULL;
505 $bundles_changed = TRUE;
511 if ($bundles_changed) {
512 $field_definition->setSetting('handler_settings', $handler_settings);
514 $changed |= $bundles_changed;
522 public function getPossibleValues(AccountInterface $account = NULL) {
523 return $this->getSettableValues($account);
529 public function getPossibleOptions(AccountInterface $account = NULL) {
530 return $this->getSettableOptions($account);
536 public function getSettableValues(AccountInterface $account = NULL) {
537 // Flatten options first, because "settable options" may contain group
539 $flatten_options = OptGroup::flattenOptions($this->getSettableOptions($account));
540 return array_keys($flatten_options);
546 public function getSettableOptions(AccountInterface $account = NULL) {
547 $field_definition = $this->getFieldDefinition();
548 if (!$options = \Drupal::service('plugin.manager.entity_reference_selection')->getSelectionHandler($field_definition, $this->getEntity())->getReferenceableEntities()) {
552 // Rebuild the array by changing the bundle key into the bundle label.
553 $target_type = $field_definition->getSetting('target_type');
554 $bundles = \Drupal::entityManager()->getBundleInfo($target_type);
557 foreach ($options as $bundle => $entity_ids) {
558 // The label does not need sanitizing since it is used as an optgroup
559 // which is only supported by select elements and auto-escaped.
560 $bundle_label = (string) $bundles[$bundle]['label'];
561 $return[$bundle_label] = $entity_ids;
564 return count($return) == 1 ? reset($return) : $return;
568 * Render API callback: Processes the field settings form and allows access to
571 * @see static::fieldSettingsForm()
573 public static function fieldSettingsAjaxProcess($form, FormStateInterface $form_state) {
574 static::fieldSettingsAjaxProcessElement($form, $form);
579 * Adds entity_reference specific properties to AJAX form elements from the
580 * field settings form.
582 * @see static::fieldSettingsAjaxProcess()
584 public static function fieldSettingsAjaxProcessElement(&$element, $main_form) {
585 if (!empty($element['#ajax'])) {
586 $element['#ajax'] = [
587 'callback' => [get_called_class(), 'settingsAjax'],
588 'wrapper' => $main_form['#id'],
589 'element' => $main_form['#array_parents'],
593 foreach (Element::children($element) as $key) {
594 static::fieldSettingsAjaxProcessElement($element[$key], $main_form);
599 * Render API callback: Moves entity_reference specific Form API elements
600 * (i.e. 'handler_settings') up a level for easier processing by the
601 * validation and submission handlers.
603 * @see _entity_reference_field_settings_process()
605 public static function formProcessMergeParent($element) {
606 $parents = $element['#parents'];
608 $element['#parents'] = $parents;
613 * Ajax callback for the handler settings form.
615 * @see static::fieldSettingsForm()
617 public static function settingsAjax($form, FormStateInterface $form_state) {
618 return NestedArray::getValue($form, $form_state->getTriggeringElement()['#ajax']['element']);
622 * Submit handler for the non-JS case.
624 * @see static::fieldSettingsForm()
626 public static function settingsAjaxSubmit($form, FormStateInterface $form_state) {
627 $form_state->setRebuild();
633 public static function getPreconfiguredOptions() {
636 // Add all the commonly referenced entity types as distinct pre-configured
638 $entity_types = \Drupal::entityManager()->getDefinitions();
639 $common_references = array_filter($entity_types, function (EntityTypeInterface $entity_type) {
640 return $entity_type->isCommonReferenceTarget();
643 /** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
644 foreach ($common_references as $entity_type) {
645 $options[$entity_type->id()] = [
646 'label' => $entity_type->getLabel(),
647 'field_storage_config' => [
649 'target_type' => $entity_type->id(),