Skip to content
entity_reference.module 9.55 KiB
Newer Older
<?php

/**
 * @file
 * Provides a field that can reference other entities.
 */

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\field\FieldConfigInterface;
function entity_reference_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.entity_reference':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Entity Reference module allows you to create fields that contain links to other entities (such as content items, taxonomy terms, etc.) within the site. This allows you, for example, to include a link to a user within a content item. For more information, see <a href="!er_do">the online documentation for the Entity Reference module</a> and the <a href="!field_help">Field module help page</a>.', array('!field_help' => \Drupal::url('help.page', array('name' => 'field')), '!er_do' => 'https://www.drupal.org/documentation/modules/entityreference')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Managing and displaying entity reference fields') . '</dt>';
      $output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the entity reference field can be configured separately. See the <a href="!field_ui">Field UI help</a> for more information on how to manage fields and their display.', array('!field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</dd>';
      $output .= '<dt>' . t('Selecting reference type') . '</dt>';
      $output .= '<dd>' . t('In the field settings you can select which type of item you want to create a reference to.') . '</dd>';
      $output .= '<dt>' . t('Filtering and sorting reference fields') . '</dt>';
      $output .= '<dd>' . t('Depending on the chosen entity type, additional filtering and sorting options are available for the list of entities that can be referred to, in the field settings. For example, the list of users can be filtered by role and sorted by name or ID.') . '</dd>';
      $output .= '<dt>' . t('Displaying a reference') . '</dt>';
      $output .= '<dd>' . t('An entity reference can be displayed as a simple label with or without a link to the entity. Alternatively, the referenced entity can be displayed as a teaser (or any other available view mode) inside the referencing entity. Certain entity types may provide additional display options. You can configure how the entity reference is displayed on the <em>Manage display</em> page for the entity.') . '</dd>';
      $output .= '<dt>' . t('Configuring form displays') . '</dt>';
      $output .= '<dd>' . t('Reference fields have several widgets available on the <em>Manage form display</em> page:');
      $output .= '<ul>';
      $output .= '<li>' . t('The <em>Check boxes/radio buttons</em> widget displays the existing entities for the entity type as check boxes or radio buttons based on the <em>Allowed number of values</em> set for the field.') . '</li>';
      $output .= '<li>' . t('The <em>Select list</em> widget displays the existing entities in a drop-down list or scrolling list box based on the <em>Allowed number of values</em> setting for the field.') . '</li>';
      $output .= '<li>' . t('The <em>Autocomplete</em> widget displays text fields in which users can type entity labels based on the <em>Allowed number of values</em>. The widget can be configured to display all entities that contain the typed characters or restricted to those starting with those characters.') . '</li>';
      $output .= '<li>' . t('The <em>Autocomplete (Tags style)</em> widget displays a multi-text field in which users can type in a comma-separated list of entity labels.') . '</li>';
      $output .= '</ul>';
 * Implements hook_field_info_alter().
function entity_reference_field_info_alter(&$info) {
  // Make the entity reference field configurable.
  $info['entity_reference']['no_ui'] = FALSE;
  $info['entity_reference']['class'] = '\Drupal\entity_reference\ConfigurableEntityReferenceItem';
  $info['entity_reference']['list_class'] = '\Drupal\Core\Field\EntityReferenceFieldItemList';
  $info['entity_reference']['default_widget'] = 'entity_reference_autocomplete';
  $info['entity_reference']['default_formatter'] = 'entity_reference_label';
  $info['entity_reference']['provider'] = 'entity_reference';
/**
 * Implements hook_field_widget_info_alter().
 */
function entity_reference_field_widget_info_alter(&$info) {
  if (isset($info['options_select'])) {
    $info['options_select']['field_types'][] = 'entity_reference';
  }
  if (isset($info['options_buttons'])) {
    $info['options_buttons']['field_types'][] = 'entity_reference';
  }
}

 * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
 *
 * Reset the instance handler settings, when the target type is changed.
 */
function entity_reference_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
  if ($field_storage->getType() != 'entity_reference') {
    // Only act on entity reference fields.
  if ($field_storage->isSyncing()) {
    // Don't change anything during a configuration sync.
    return;
  }

  if ($field_storage->getSetting('target_type') == $field_storage->original->getSetting('target_type')) {
  foreach ($field_storage->getBundles() as $bundle) {
    $field = FieldConfig::loadByName($field_storage->getTargetEntityTypeId(), $bundle, $field_storage->getName());
    $field->setSetting('handler_settings', []);
/**
 * Implements hook_ENTITY_TYPE_presave() for 'field_config'.
 *
 * Determine the selection handler plugin ID for an entity reference field.
 */
function entity_reference_field_config_presave(FieldConfigInterface $field) {
  if ($field->getType() != 'entity_reference') {
    // Only act on entity reference fields.
    return;
  }
  if ($field->isSyncing()) {
    // Don't change anything during a configuration sync.
    return;

  $target_type = $field->getFieldStorageDefinition()->getSetting('target_type');
  $selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
  list($current_handler) = explode(':', $field->getSetting('handler'), 2);
  $field->setSetting('handler', $selection_manager->getPluginId($target_type, $current_handler));
/**
 * Implements hook_form_FORM_ID_alter() for 'field_ui_field_storage_add_form'.
 */
function entity_reference_form_field_ui_field_storage_add_form_alter(array &$form) {
  $optgroup = (string) t('Reference');
  // Move the "Entity reference" option to the end of the list and rename it to
  // "Other".
  unset($form['add']['new_storage_type']['#options'][$optgroup]['entity_reference']);
  $form['add']['new_storage_type']['#options'][$optgroup]['entity_reference'] = t('Other…');
 * Render API callback: Processes the field settings form and allows access to
 * the form state.
 * @see entity_reference_field_field_settings_form()
function _entity_reference_field_field_settings_ajax_process($form, FormStateInterface $form_state) {
  _entity_reference_field_field_settings_ajax_process_element($form, $form);
  return $form;
}

/**
 * Adds entity_reference specific properties to AJAX form elements from the
 * @see _entity_reference_field_field_settings_ajax_process()
function _entity_reference_field_field_settings_ajax_process_element(&$element, $main_form) {
  if (!empty($element['#ajax'])) {
    $element['#ajax'] = array(
      'callback' => 'entity_reference_settings_ajax',
      'wrapper' => $main_form['#id'],
      'element' => $main_form['#array_parents'],
    );
  }

  foreach (Element::children($element) as $key) {
    _entity_reference_field_field_settings_ajax_process_element($element[$key], $main_form);
  }
}

/**
 * Render API callback: Moves entity_reference specific Form API elements
 * (i.e. 'handler_settings') up a level for easier processing by the validation
 * and submission handlers.
 *
 * @see _entity_reference_field_settings_process()
 */
function _entity_reference_form_process_merge_parent($element) {
  $parents = $element['#parents'];
  array_pop($parents);
  $element['#parents'] = $parents;
  return $element;
}

/**
 * Form element validation handler; Filters the #value property of an element.
 */
function _entity_reference_element_validate_filter(&$element, FormStateInterface $form_state) {
  $element['#value'] = array_filter($element['#value']);
  $form_state->setValueForElement($element, $element['#value']);
 * @see entity_reference_field_field_settings_form()
function entity_reference_settings_ajax($form, FormStateInterface $form_state) {
  return NestedArray::getValue($form, $form_state->getTriggeringElement()['#ajax']['element']);
 * @see entity_reference_field_field_settings_form()
function entity_reference_settings_ajax_submit($form, FormStateInterface $form_state) {
}

/**
 * Implements hook_query_TAG_alter().
 */
function entity_reference_query_entity_reference_alter(AlterableInterface $query) {
  $handler = $query->getMetadata('entity_reference_selection_handler');
  $handler->entityQueryAlter($query);
}