entity_reference.module 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

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

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Entity\EntityInterface;
11
use Drupal\Core\Entity\Field\FieldDefinitionInterface;
12
use Drupal\field\FieldInterface;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

/**
 * Implements hook_field_info().
 */
function entity_reference_field_info() {
  $field_info['entity_reference'] = array(
    'label' => t('Entity Reference'),
    'description' => t('This field references another entity.'),
    'settings' => array(
      // Default to a primary entity type (i.e. node or user).
      'target_type' => module_exists('node') ? 'node' : 'user',
    ),
    'instance_settings' => array(
      // The selection handler for this instance.
      'handler' => 'default',
      // The handler settings.
      'handler_settings' => array(),
    ),
    'default_widget' => 'entity_reference_autocomplete',
    'default_formatter' => 'entity_reference_label',
33
    'class' => '\Drupal\entity_reference\Type\ConfigurableEntityReferenceItem',
34 35 36 37 38
  );
  return $field_info;
}

/**
39
 * Implements hook_entity_field_info_alter().
40 41 42
 *
 * Set the "target_type" property definition for entity reference fields.
 *
43
 * @see \Drupal\Core\Entity\Plugin\DataType\EntityReferenceItem::getPropertyDefinitions()
44 45 46 47 48
 *
 * @param array $info
 *   The property info array as returned by hook_entity_field_info().
 * @param string $entity_type
 *   The entity type for which entity properties are defined.
49
 */
50
function entity_reference_entity_field_info_alter(&$info, $entity_type) {
51 52 53 54 55 56
  foreach (field_info_instances($entity_type) as $bundle_name => $instances) {
    foreach ($instances as $field_name => $instance) {
      $field = field_info_field($field_name);
      if ($field['type'] != 'entity_reference') {
        continue;
      }
57 58 59 60 61 62
      if (isset($info['definitions'][$field_name])) {
        $info['definitions'][$field_name]['settings']['target_type'] = $field['settings']['target_type'];
      }
      elseif (isset($info['optional'][$field_name])) {
        $info['optional'][$field_name]['settings']['target_type'] = $field['settings']['target_type'];
      }
63 64 65 66
    }
  }
}

67 68 69 70 71 72 73 74 75 76 77 78
/**
 * 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';
  }
}

79 80 81 82 83
/**
 * Gets the selection handler for a given entity_reference field.
 *
 * @return \Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface
 */
84
function entity_reference_get_selection_handler(FieldDefinitionInterface $field_definition, EntityInterface $entity = NULL) {
85
  $options = array(
86
    'field_definition' => $field_definition,
87 88
    'entity' => $entity,
  );
89
  return Drupal::service('plugin.manager.entity_reference.selection')->getInstance($options);
90 91 92 93 94 95 96 97 98
}

/**
 * Implements hook_field_presave().
 *
 * Create an entity on the fly.
 */
function entity_reference_field_presave(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  foreach ($items as $delta => $item) {
99
    if (empty($item['target_id']) && !empty($item['entity']) && $item['entity']->isNew()) {
100 101
      $item['entity']->save();
      $items[$delta]['target_id'] = $item['entity']->id();
102 103 104 105 106 107 108 109 110 111
    }
  }
}

/**
 * Implements hook_field_validate().
 */
function entity_reference_field_validate(EntityInterface $entity = NULL, $field, $instance, $langcode, $items, &$errors) {
  $ids = array();
  foreach ($items as $delta => $item) {
112
    if (!empty($item['target_id']) && (!empty($item['entity']) && !$item['entity']->isNew())) {
113 114 115 116 117
      $ids[$item['target_id']] = $delta;
    }
  }

  if ($ids) {
118
    $valid_ids = entity_reference_get_selection_handler($instance, $entity)->validateReferenceableEntities(array_keys($ids));
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

    $invalid_entities = array_diff_key($ids, array_flip($valid_ids));
    if ($invalid_entities) {
      foreach ($invalid_entities as $id => $delta) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'entity_reference_invalid_entity',
          'message' => t('The referenced entity (@type: @id) does not exist.', array('@type' => $field['settings']['target_type'], '@id' => $id)),
        );
      }
    }
  }
}

/**
 * Implements hook_field_settings_form().
 */
135
function entity_reference_field_settings_form($field, $instance) {
136 137 138
  // Select the target entity type.
  $entity_type_options = array();
  foreach (entity_get_info() as $entity_type => $entity_info) {
139 140 141 142
    // @todo As the database schema can currently only store numeric IDs of
    // referenced entities and configuration entities have string IDs, prevent
    // configuration entities from being referenced.
    if (!in_array('\Drupal\Core\Config\Entity\ConfigEntityInterface', class_implements($entity_info['class']))) {
143 144 145 146 147 148
      $entity_type_options[$entity_type] = $entity_info['label'];
    }
  }

  $form['target_type'] = array(
    '#type' => 'select',
149
    '#title' => t('Type of item to reference'),
150 151 152
    '#options' => $entity_type_options,
    '#default_value' => $field['settings']['target_type'],
    '#required' => TRUE,
153
    '#disabled' => $field->hasData(),
154 155 156 157 158 159 160
    '#size' => 1,
  );

  return $form;
}

/**
161
 * Implements hook_ENTITY_TYPE_update() for 'field_entity'.
162 163 164
 *
 * Reset the instance handler settings, when the target type is changed.
 */
165 166 167
function entity_reference_field_entity_update(FieldInterface $field) {
  if ($field->type != 'entity_reference') {
    // Only act on entity reference fields.
168 169 170
    return;
  }

171
  if ($field->settings['target_type'] == $field->original->settings['target_type']) {
172 173 174 175
    // Target type didn't change.
    return;
  }

176
  if (empty($field->bundles)) {
177 178 179 180
    // Field has no instances.
    return;
  }

181
  $field_name = $field->id();
182

183
  foreach ($field->bundles() as $entity_type => $bundles) {
184 185
    foreach ($bundles as $bundle) {
      $instance = field_info_instance($entity_type, $field_name, $bundle);
186 187
      $instance->settings['handler_settings'] = array();
      $instance->save();
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    }
  }
}

/**
 * Implements hook_field_instance_settings_form().
 */
function entity_reference_field_instance_settings_form($field, $instance, $form_state) {
  $field = isset($form_state['entity_reference']['field']) ? $form_state['entity_reference']['field'] : $field;
  $instance = isset($form_state['entity_reference']['instance']) ? $form_state['entity_reference']['instance'] : $instance;

  $settings = $instance['settings'];
  $settings += array('handler' => 'default');

  // Get all selection plugins for this entity type.
203
  $selection_plugins = Drupal::service('plugin.manager.entity_reference.selection')->getSelectionGroups($field['settings']['target_type']);
204 205
  $handler_groups = array_keys($selection_plugins);

206
  $handlers = Drupal::service('plugin.manager.entity_reference.selection')->getDefinitions();
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  $handlers_options = array();
  foreach ($handlers as $plugin_id => $plugin) {
    // We only display base plugins (e.g. 'base', 'views', ..) and not entity
    // type specific plugins (e.g. 'base_node', 'base_user', ...).
    if (in_array($plugin_id, $handler_groups)) {
      $handlers_options[$plugin_id] = check_plain($plugin['label']);
    }
  }

  $form = array(
    '#type' => 'container',
    '#attached' => array(
      'css' => array(drupal_get_path('module', 'entity_reference') . '/css/entity_reference.admin.css'),
    ),
    '#process' => array(
      '_entity_reference_field_instance_settings_ajax_process',
    ),
    '#element_validate' => array('_entity_reference_field_instance_settings_validate'),
    '#field' => $field,
    '#instance' => $instance,
  );
  $form['handler'] = array(
    '#type' => 'details',
    '#title' => t('Reference type'),
    '#tree' => TRUE,
    '#process' => array('_entity_reference_form_process_merge_parent'),
  );

  $form['handler']['handler'] = array(
    '#type' => 'select',
    '#title' => t('Reference method'),
    '#options' => $handlers_options,
    '#default_value' => $settings['handler'],
    '#required' => TRUE,
    '#ajax' => TRUE,
    '#limit_validation_errors' => array(),
  );
  $form['handler']['handler_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Change handler'),
    '#limit_validation_errors' => array(),
    '#attributes' => array(
      'class' => array('js-hide'),
    ),
    '#submit' => array('entity_reference_settings_ajax_submit'),
  );

  $form['handler']['handler_settings'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('entity_reference-settings')),
  );

259
  $handler = entity_reference_get_selection_handler($instance);
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  $form['handler']['handler_settings'] += $handler->settingsForm($field, $instance);

  return $form;
}

/**
 * Render API callback: Processes the field instance settings form and allows
 * access to the form state.
 *
 * @see entity_reference_field_instance_settings_form()
 */
function _entity_reference_field_instance_settings_ajax_process($form, $form_state) {
  _entity_reference_field_instance_settings_ajax_process_element($form, $form);
  return $form;
}

/**
 * Adds entity_reference specific properties to AJAX form elements from the
 * field instance settings form.
 *
 * @see _entity_reference_field_instance_settings_ajax_process()
 */
function _entity_reference_field_instance_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_instance_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, &$form_state) {
  $element['#value'] = array_filter($element['#value']);
  form_set_value($element, $element['#value'], $form_state);
}

/**
 * Form element validation handler; Stores the new values in the form state.
 *
 * @see entity_reference_field_instance_settings_form()
 */
function _entity_reference_field_instance_settings_validate($form, &$form_state) {
  $instance = $form['#instance'];
  if (isset($form_state['values']['instance'])) {
    $instance['settings'] = $form_state['values']['instance']['settings'];
  }
  $form_state['entity_reference']['instance'] = $instance;

  unset($form_state['values']['instance']['settings']['handler_submit']);
}

/**
 * Ajax callback for the handler settings form.
 *
 * @see entity_reference_field_instance_settings_form()
 */
function entity_reference_settings_ajax($form, $form_state) {
  $trigger = $form_state['triggering_element'];
  return NestedArray::getValue($form, $trigger['#ajax']['element']);
}

/**
 * Submit handler for the non-JS case.
 *
 * @see entity_reference_field_instance_settings_form()
 */
function entity_reference_settings_ajax_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

/**
 * Implements hook_options_list().
 */
355
function entity_reference_options_list(FieldDefinitionInterface $field_definition, EntityInterface $entity) {
356
  if (!$options = entity_reference_get_selection_handler($field_definition, $entity)->getReferenceableEntities()) {
357 358 359 360
    return array();
  }

  // Rebuild the array by changing the bundle key into the bundle label.
361
  $target_type = $field_definition->getFieldSetting('target_type');
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
  $bundles = entity_get_bundles($target_type);

  $return = array();
  foreach ($options as $bundle => $entity_ids) {
    $bundle_label = check_plain($bundles[$bundle]['label']);
    $return[$bundle_label] = $entity_ids;
  }

  return count($return) == 1 ? reset($return) : $return;
}

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

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
/**
 * Creates an instance of a entity reference field on the specified bundle.
 *
 * @param string $entity_type
 *   The type of entity the field instance will be attached to.
 * @param string $bundle
 *   The bundle name of the entity the field instance will be attached to.
 * @param string $field_name
 *   The name of the field; if it already exists, a new instance of the existing
 *   field will be created.
 * @param string $field_label
 *   The label of the field instance.
 * @param string $target_entity_type
 *   The type of the referenced entity.
 * @param string $selection_handler
 *   The selection handler used by this field.
 * @param array $selection_handler_settings
 *   An array of settings supported by the selection handler specified above.
 *   (e.g. 'target_bundles', 'sort', 'auto_create', etc).
 *
 * @see \Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase::settingsForm()
 */
function entity_reference_create_instance($entity_type, $bundle, $field_name, $field_label, $target_entity_type, $selection_handler = 'default', $selection_handler_settings = array()) {
  // If a field type we know should exist isn't found, clear the field cache.
  if (!field_info_field_types('entity_reference')) {
    field_cache_clear();
  }

  // Look for or add the specified field to the requested entity bundle.
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle);

  if (empty($field)) {
    $field = array(
      'field_name' => $field_name,
      'type' => 'entity_reference',
      'entity_types' => array($entity_type),
      'settings' => array(
        'target_type' => $target_entity_type,
      ),
    );
422
    entity_create('field_entity', $field)->save();
423 424 425 426 427 428 429 430 431 432 433 434 435
  }

  if (empty($instance)) {
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => $field_label,
      'settings' => array(
        'handler' => $selection_handler,
        'handler_settings' => $selection_handler_settings,
      ),
    );
436
    entity_create('field_instance', $instance)->save();
437 438
  }
}
439