field.attach.inc 58 KB
Newer Older
1 2
<?php

3 4
/**
 * @file
5
 * Field attach API, allowing entities (nodes, users, ...) to be 'fieldable'.
6 7
 */

8
use Drupal\field\FieldValidationException;
9
use Drupal\Core\Entity\EntityInterface;
10

11 12 13
/**
 * @defgroup field_storage Field Storage API
 * @{
14
 * Implements a storage engine for Field API data.
15
 *
16 17 18 19 20 21 22
 * The Field Attach API uses the Field Storage API to perform all "database
 * access". Each Field Storage API hook function defines a primitive database
 * operation such as read, write, or delete. The default field storage module,
 * field_sql_storage.module, uses the local SQL database to implement these
 * operations, but alternative field storage backends can choose to represent
 * the data in SQL differently or use a completely different storage mechanism
 * such as a cloud-based database.
23
 *
24
 * Each field defines which storage backend it uses. The Drupal system variable
25
 * 'field_storage_default' identifies the storage backend used by default.
26
 *
27 28
 * See @link field Field API @endlink for information about the other parts of
 * the Field API.
29
 */
30 31

/**
32 33
 * Argument for an update operation.
 *
34
 * This is used in hook_field_storage_write when updating an existing entity.
35
 */
36
const FIELD_STORAGE_UPDATE = 'update';
37 38

/**
39 40
 * Argument for an insert operation.
 *
41
 * This is used in hook_field_storage_write when inserting a new entity.
42
 */
43
const FIELD_STORAGE_INSERT = 'insert';
44

45
/**
46
 * @} End of "defgroup field_storage".
47 48 49 50 51
 */

/**
 * @defgroup field_attach Field Attach API
 * @{
52
 * Operates on Field API data attached to Drupal entities.
53
 *
54
 * Field Attach API functions load, store, display, generate Field API
55 56 57 58 59 60 61 62
 * structures, and perform a variety of other functions for field data attached
 * to individual entities.
 *
 * Field Attach API functions generally take $entity_type and $entity arguments
 * along with additional function-specific arguments. $entity_type is the type
 * of the fieldable entity, such as 'node' or 'user', and $entity is the entity
 * itself.
 *
63 64 65
 * hook_entity_info() is the central place for entity types to define if and how
 * Field API should operate on their entity objects. Notably, the 'fieldable'
 * property needs to be set to TRUE.
66 67 68 69 70 71
 *
 * The Field Attach API uses the concept of bundles: the set of fields for a
 * given entity is defined on a per-bundle basis. The collection of bundles for
 * an entity type is defined its hook_entity_info() implementation. For
 * instance, node_entity_info() exposes each node type as its own bundle. This
 * means that the set of fields of a node is determined by the node type. The
72 73 74
 * Field API reads the bundle name for a given entity from a particular property
 * of the entity object, and hook_entity_info() defines which property to use.
 * For instance, node_entity_info() specifies:
75 76 77 78 79 80 81 82 83 84
 * @code $info['entity keys']['bundle'] = 'type'@endcode
 * This indicates that for a particular node object, the bundle name can be
 * found in $node->type. This property can be omitted if the entity type only
 * exposes a single bundle (all entities of this type have the same collection
 * of fields). This is the case for the 'user' entity type.
 *
 * Most Field Attach API functions define a corresponding hook function that
 * allows any module to act on Field Attach operations for any entity after the
 * operation is complete, and access or modify all the field, form, or display
 * data for that entity and operation. For example, field_attach_view() invokes
85
 * hook_field_attach_view_alter(). These all-module hooks are distinct from
86 87 88 89 90
 * those of the Field Types API, such as hook_field_load(), that are only
 * invoked for the module that defines a specific field type.
 *
 * field_attach_load(), field_attach_insert(), and field_attach_update() also
 * define pre-operation hooks, e.g. hook_field_attach_pre_load(). These hooks
91 92
 * run before the corresponding Field Storage API and Field Type API operations.
 * They allow modules to define additional storage locations (e.g.
93 94 95 96 97 98
 * denormalizing, mirroring) for field data on a per-field basis. They also
 * allow modules to take over field storage completely by instructing other
 * implementations of the same hook and the Field Storage API itself not to
 * operate on specified fields.
 *
 * The pre-operation hooks do not make the Field Storage API irrelevant. The
99 100
 * Field Storage API is essentially the "fallback mechanism" for any fields that
 * aren't being intercepted explicitly by pre-operation hooks.
101
 *
102 103 104
 * @link field_language Field language API @endlink provides information about
 * the structure of field objects.
 *
105 106
 * See @link field Field API @endlink for information about the other parts of
 * the Field API.
107 108
 */

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/**
 * Invoke a method on all the fields of a given entity.
 *
 * @todo Remove _field_invoke() and friends when field types and formatters are
 * turned into plugins.
 *
 * @param string $method
 *   The name of the method to invoke.
 * @param Closure $target
 *   A closure that receives an $instance object and returns the object on
 *   which the method should be invoked.
 * @param Drupal\Core\Entity\EntityInterface $entity
 *   The fully formed $entity_type entity.
 * @param mixed $a
 *   A parameter for the invoked method. Defaults to NULL.
 * @param mixed $b
 *   A parameter for the invoked method. Defaults to NULL.
 * @param array $options
 *   An associative array of additional options, with the following keys:
 *   - field_name: The name of the field whose operation should be invoked. By
 *     default, the operation is invoked on all the fields in the entity's
 *     bundle. NOTE: This option is not compatible with the 'deleted' option;
 *     the 'field_id' option should be used instead.
 *   - field_id: The ID of the field whose operation should be invoked. By
 *     default, the operation is invoked on all the fields in the entity's'
 *     bundles.
 *   - deleted: If TRUE, the function will operate on deleted fields as well
 *     as non-deleted fields. If unset or FALSE, only non-deleted fields are
 *     operated on.
 *   - langcode: A language code or an array of language codes keyed by field
 *     name. It will be used to narrow down to a single value the available
 *     languages to act on.
 */
function field_invoke_method($method, \Closure $target_closure, EntityInterface $entity, &$a = NULL, &$b = NULL, array $options = array()) {
  // Merge default options.
  $default_options = array(
    'deleted' => FALSE,
    'langcode' => NULL,
  );
  $options += $default_options;

  $entity_type = $entity->entityType();
  // Determine the list of instances to iterate on.
  $instances = _field_invoke_get_instances($entity_type, $entity->bundle(), $options);

  // Iterate through the instances and collect results.
  $return = array();
  foreach ($instances as $instance) {

    // Let the closure determine the target object on which the method should be
    // called.
    $target = $target_closure($instance);

    if (method_exists($target, $method)) {
      $field = field_info_field_by_id($instance['field_id']);
      $field_name = $field['field_name'];

      // Determine the list of languages to iterate on.
      $available_langcodes = field_available_languages($entity_type, $field);
      $langcodes = _field_language_suggestion($available_langcodes, $options['langcode'], $field_name);

      foreach ($langcodes as $langcode) {
        $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();

        $result = $target->$method($entity, $langcode, $items, $a, $b);

        if (isset($result)) {
          // For methods with array results, we merge results together.
          // For methods with scalar results, we collect results in an array.
          if (is_array($result)) {
            $return = array_merge($return, $result);
          }
          else {
            $return[] = $result;
          }
        }

        // Populate $items back in the field values, but avoid replacing missing
        // fields with an empty array (those are not equivalent on update).
        if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
          $entity->{$field_name}[$langcode] = $items;
        }
      }
    }
  }

  return $return;
}

198 199 200 201
/**
 * Invoke a field hook.
 *
 * @param $op
202
 *   Possible operations include:
203 204 205 206 207 208 209 210 211
 *   - form
 *   - validate
 *   - presave
 *   - insert
 *   - update
 *   - delete
 *   - delete revision
 *   - view
 *   - prepare translation
212 213
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
214
 * @param Drupal\Core\Entity\EntityInterface $entity
215
 *   The fully formed $entity_type entity.
216
 * @param $a
217
 *   - The $form in the 'form' operation.
218
 *   - The value of $view_mode in the 'view' operation.
219
 *   - Otherwise NULL.
220
 * @param $b
221 222
 *   - The $form_state in the 'submit' operation.
 *   - Otherwise NULL.
223 224
 * @param $options
 *   An associative array of additional options, with the following keys:
225 226
 *  - 'field_name': The name of the field whose operation should be
 *    invoked. By default, the operation is invoked on all the fields
227
 *    in the entity's bundle. NOTE: This option is not compatible with
228
 *    the 'deleted' option; the 'field_id' option should be used
229
 *    instead.
230 231
 *  - 'field_id': The id of the field whose operation should be
 *    invoked. By default, the operation is invoked on all the fields
232
 *    in the entity's' bundles.
233 234
 *  - 'default': A boolean value, specifying which implementation of
 *    the operation should be invoked.
235 236 237 238 239 240
 *    - if FALSE (default), the field types implementation of the operation
 *      will be invoked (hook_field_[op])
 *    - If TRUE, the default field implementation of the field operation
 *      will be invoked (field_default_[op])
 *    Internal use only. Do not explicitely set to TRUE, but use
 *    _field_invoke_default() instead.
241 242 243
 *  - 'deleted': If TRUE, the function will operate on deleted fields
 *    as well as non-deleted fields. If unset or FALSE, only
 *    non-deleted fields are operated on.
244
 *  - 'langcode': A language code or an array of language codes keyed by field
245 246
 *    name. It will be used to narrow down to a single value the available
 *    languages to act on.
247
 */
248
function _field_invoke($op, $entity_type, EntityInterface $entity, &$a = NULL, &$b = NULL, $options = array()) {
249 250 251
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
252
    'deleted' => FALSE,
253
    'langcode' => NULL,
254 255 256
  );
  $options += $default_options;

257
  // Determine the list of instances to iterate on.
258
  $instances = _field_invoke_get_instances($entity_type, $entity->bundle(), $options);
259

260 261
  // Iterate through the instances and collect results.
  $return = array();
262
  foreach ($instances as $instance) {
263 264 265 266
    // field_info_field() is not available for deleted fields, so use
    // field_info_field_by_id().
    $field = field_info_field_by_id($instance['field_id']);
    $field_name = $field['field_name'];
267 268 269
    $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
    if (function_exists($function)) {
      // Determine the list of languages to iterate on.
270 271
      $available_langcodes = field_available_languages($entity_type, $field);
      $langcodes = _field_language_suggestion($available_langcodes, $options['langcode'], $field_name);
272

273
      foreach ($langcodes as $langcode) {
274 275 276 277 278 279 280
        $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
        $result = $function($entity_type, $entity, $field, $instance, $langcode, $items, $a, $b);
        if (isset($result)) {
          // For hooks with array results, we merge results together.
          // For hooks with scalar results, we collect results in an array.
          if (is_array($result)) {
            $return = array_merge($return, $result);
281
          }
282 283
          else {
            $return[] = $result;
284 285
          }
        }
286 287 288 289 290 291

        // Populate $items back in the field values, but avoid replacing missing
        // fields with an empty array (those are not equivalent on update).
        if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
          $entity->{$field_name}[$langcode] = $items;
        }
292 293 294 295 296 297 298
      }
    }
  }

  return $return;
}

299
/**
300
 * Invokes a field hook across fields on multiple entities.
301 302 303 304
 *
 * @param $op
 *   Possible operations include:
 *   - load
305
 *   - prepare_view
306 307
 *   For all other operations, use _field_invoke() / field_invoke_default()
 *   instead.
308
 * @param $entity_type
309
 *   The type of entities in $entities; e.g. 'node' or 'user'.
310
 * @param $entities
311
 *   An array of entities, keyed by entity ID.
312 313 314 315 316
 * @param $a
 *   - The $age parameter in the 'load' operation.
 *   - Otherwise NULL.
 * @param $b
 *   Currently always NULL.
317 318
 * @param $options
 *   An associative array of additional options, with the following keys:
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
 *   - field_name: The name of the field whose operation should be invoked. By
 *     default, the operation is invoked on all the fields in the entity's
 *     bundle. NOTE: This option is not compatible with the 'deleted' option;
 *     the 'field_id' option should be used instead.
 *   - field_id: The ID of the field whose operation should be invoked. By
 *     default, the operation is invoked on all the fields in the entity's
 *     bundles.
 *   - default: A boolean value, specifying which implementation of the
 *     operation should be invoked.
 *     - if FALSE (default), the field types implementation of the operation
 *       will be invoked (hook_field_[op])
 *     - If TRUE, the default field implementation of the field operation will
 *       be invoked (field_default_[op])
 *     Internal use only. Do not explicitely set to TRUE, but use
 *     _field_invoke_multiple_default() instead.
 *   - deleted: If TRUE, the function will operate on deleted fields as well as
 *     non-deleted fields. If unset or FALSE, only non-deleted fields are
 *     operated on.
 *   - langcode: A language code or an array of arrays of language codes keyed
 *     by entity ID and field name. It will be used to narrow down to a single
 *     value the available languages to act on.
340
 *
341
 * @return
342
 *   An array of returned values keyed by entity ID.
343
 */
344
function _field_invoke_multiple($op, $entity_type, $entities, &$a = NULL, &$b = NULL, $options = array()) {
345 346 347
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
348
    'deleted' => FALSE,
349
    'langcode' => NULL,
350 351
  );
  $options += $default_options;
352
  $field_info = field_info_field_by_ids();
353

354 355
  $fields = array();
  $grouped_instances = array();
356
  $grouped_entities = array();
357 358 359
  $grouped_items = array();
  $return = array();

360
  // Go through the entities and collect the fields on which the hook should be
361
  // invoked.
362
  //
363
  // We group fields by ID, not by name, because this function can operate on
364
  // deleted fields which may have non-unique names. However, entities can only
365 366
  // contain data for a single field for each name, even if that field
  // is deleted, so we reference field data via the
367 368
  // $entity->$field_name property.
  foreach ($entities as $entity) {
369
    // Determine the list of instances to iterate on.
370 371
    $instances = _field_invoke_get_instances($entity_type, $entity->bundle(), $options);
    $id = $entity->id();
372 373 374

    foreach ($instances as $instance) {
      $field_id = $instance['field_id'];
375
      $field_name = $instance['field_name'];
376
      $field = $field_info[$field_id];
377 378
      $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
      if (function_exists($function)) {
379
        // Add the field to the list of fields to invoke the hook on.
380
        if (!isset($fields[$field_id])) {
381
          $fields[$field_id] = $field;
382 383 384
        }
        // Extract the field values into a separate variable, easily accessed
        // by hook implementations.
385 386 387 388 389 390
        // Unless a language code suggestion is provided we iterate on all the
        // available language codes.
        $available_langcodes = field_available_languages($entity_type, $field);
        $langcode = !empty($options['langcode'][$id]) ? $options['langcode'][$id] : $options['langcode'];
        $langcodes = _field_language_suggestion($available_langcodes, $langcode, $field_name);
        foreach ($langcodes as $langcode) {
391
          $grouped_items[$field_id][$langcode][$id] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
392 393 394 395
          // Group the instances and entities corresponding to the current
          // field.
          $grouped_instances[$field_id][$langcode][$id] = $instance;
          $grouped_entities[$field_id][$langcode][$id] = $entities[$id];
396
        }
397 398
      }
    }
399
    // Initialize the return value for each entity.
400 401 402
    $return[$id] = array();
  }

403
  // For each field, invoke the field hook and collect results.
404 405
  foreach ($fields as $field_id => $field) {
    $field_name = $field['field_name'];
406
    $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
407
    // Iterate over all the field translations.
408 409 410 411
    foreach ($grouped_items[$field_id] as $langcode => &$items) {
      $entities = $grouped_entities[$field_id][$langcode];
      $instances = $grouped_instances[$field_id][$langcode];
      $results = $function($entity_type, $entities, $field, $instances, $langcode, $items, $a, $b);
412 413 414 415 416 417 418 419 420 421
      if (isset($results)) {
        // Collect results by entity.
        // For hooks with array results, we merge results together.
        // For hooks with scalar results, we collect results in an array.
        foreach ($results as $id => $result) {
          if (is_array($result)) {
            $return[$id] = array_merge($return[$id], $result);
          }
          else {
            $return[$id][] = $result;
422 423 424 425 426
          }
        }
      }
    }

427
    // Populate field values back in the entities, but avoid replacing missing
428
    // fields with an empty array (those are not equivalent on update).
429 430 431
    foreach ($grouped_entities[$field_id] as $langcode => $entities) {
      foreach ($entities as $id => $entity) {
        if ($grouped_items[$field_id][$langcode][$id] !== array() || isset($entity->{$field_name}[$langcode])) {
432
          $entity->{$field_name}[$langcode] = $grouped_items[$field_id][$langcode][$id];
433
        }
434 435 436 437 438 439 440
      }
    }
  }

  return $return;
}

441 442
/**
 * Invoke field.module's version of a field hook.
443 444 445 446 447
 *
 * This function invokes the field_default_[op]() function.
 * Use _field_invoke() to invoke the field type implementation,
 * hook_field_[op]().
 *
448
 * @see _field_invoke()
449
 */
450
function _field_invoke_default($op, $entity_type, EntityInterface $entity, &$a = NULL, &$b = NULL, $options = array()) {
451
  $options['default'] = TRUE;
452
  return _field_invoke($op, $entity_type, $entity, $a, $b, $options);
453 454
}

455
/**
456
 * Invoke field.module's version of a field hook on multiple entities.
457 458 459 460 461
 *
 * This function invokes the field_default_[op]() function.
 * Use _field_invoke_multiple() to invoke the field type implementation,
 * hook_field_[op]().
 *
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
 * @param $op
 *   Possible operations include:
 *   - load
 *   - prepare_view
 *   For all other operations, use _field_invoke() / field_invoke_default()
 *   instead.
 * @param $entity_type
 *   The type of entities in $entities; e.g. 'node' or 'user'.
 * @param $entities
 *   An array of entities, keyed by entity ID.
 * @param $a
 *   - The $age parameter in the 'load' operation.
 *   - Otherwise NULL.
 * @param $b
 *   Currently always NULL.
 * @param $options
 *   An associative array of additional options, with the following keys:
 *   - field_name: The name of the field whose operation should be invoked. By
 *     default, the operation is invoked on all the fields in the entity's
 *     bundle. NOTE: This option is not compatible with the 'deleted' option;
 *     the 'field_id' option should be used instead.
 *   - field_id: The ID of the field whose operation should be invoked. By
 *     default, the operation is invoked on all the fields in the entity's
 *     bundles.
 *   - default': A boolean value, specifying which implementation of the
 *     operation should be invoked.
 *     - if FALSE (default), the field types implementation of the operation
 *       will be invoked (hook_field_[op])
 *     - If TRUE, the default field implementation of the field operation will
 *       be invoked (field_default_[op])
 *     Internal use only. Do not explicitely set to TRUE, but use
 *     _field_invoke_multiple_default() instead.
 *   - deleted: If TRUE, the function will operate on deleted fields as well as
 *     non-deleted fields. If unset or FALSE, only non-deleted fields are
 *     operated on.
 *   - language: A language code or an array of arrays of language codes keyed
 *     by entity ID and field name. It will be used to narrow down to a single
 *     value the available languages to act on.
 *
 * @return
 *   An array of returned values keyed by entity ID.
 *
504
 * @see _field_invoke_multiple()
505
 */
506
function _field_invoke_multiple_default($op, $entity_type, $entities, &$a = NULL, &$b = NULL, $options = array()) {
507
  $options['default'] = TRUE;
508
  return _field_invoke_multiple($op, $entity_type, $entities, $a, $b, $options);
509 510
}

511
/**
512 513 514
 * Retrieves a list of instances to operate on.
 *
 * Helper for _field_invoke().
515 516 517 518 519 520 521
 *
 * @param $entity_type
 *   The entity type.
 * @param $bundle
 *   The bundle name.
 * @param $options
 *   An associative array of options, as provided to _field_invoke(). Only the
522
 *   following keys are considered:
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
 *   - deleted
 *   - field_name
 *   - field_id
 *   See _field_invoke() for details.
 *
 * @return
 *   The array of selected instance definitions.
 */
function _field_invoke_get_instances($entity_type, $bundle, $options) {
  if ($options['deleted']) {
    // Deleted fields are not included in field_info_instances(), and need to
    // be fetched from the database with field_read_instances().
    $params = array('entity_type' => $entity_type, 'bundle' => $bundle);
    if (isset($options['field_id'])) {
      // Single-field mode by field id: field_read_instances() does the filtering.
      // Single-field mode by field name is not compatible with the 'deleted'
      // option.
      $params['field_id'] = $options['field_id'];
    }
    $instances = field_read_instances($params, array('include_deleted' => TRUE));
  }
  elseif (isset($options['field_name'])) {
    // Single-field mode by field name: field_info_instance() does the
    // filtering.
    $instances = array(field_info_instance($entity_type, $options['field_name'], $bundle));
  }
  else {
    $instances = field_info_instances($entity_type, $bundle);
    if (isset($options['field_id'])) {
      // Single-field mode by field id: we need to loop on each instance to
      // find the right one.
      foreach ($instances as $instance) {
        if ($instance['field_id'] == $options['field_id']) {
          $instances = array($instance);
          break;
        }
      }
    }
  }

  return $instances;
}

566 567 568 569 570 571 572 573 574 575 576 577 578 579
/**
 * Defines a 'target closure' for field_invoke_method().
 *
 * Used to invoke methods on an instance's widget.
 *
 * @return Closure
 *   A 'target closure' for field_invoke_method().
 */
function _field_invoke_widget_target() {
  return function ($instance) {
    return $instance->getWidget();
  };
}

580
/**
581
 * Adds form elements for all fields for an entity to a form structure.
582
 *
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
 * The form elements for the entity's fields are added by reference as direct
 * children in the $form parameter. This parameter can be a full form structure
 * (most common case for entity edit forms), or a sub-element of a larger form.
 *
 * By default, submitted field values appear at the top-level of
 * $form_state['values']. A different location within $form_state['values'] can
 * be specified by setting the '#parents' property on the incoming $form
 * parameter. Because of name clashes, two instances of the same field cannot
 * appear within the same $form element, or within the same '#parents' space.
 *
 * For each call to field_attach_form(), field values are processed by calling
 * field_attach_form_validate() and field_attach_submit() on the same $form
 * element.
 *
 * Sample resulting structure in $form:
598
 * @code
599 600 601 602
 *   '#parents' => The location of field values in $form_state['values'],
 *   '#entity_type' => The name of the entity type,
 *   '#bundle' => The name of the bundle,
 *   // One sub-array per field appearing in the entity, keyed by field name.
603 604 605 606 607 608 609 610 611 612 613
 *   // The structure of the array differs slightly depending on whether the
 *   // widget is 'single-value' (provides the input for one field value,
 *   // most common case), and will therefore be repeated as many times as
 *   // needed, or 'multiple-values' (one single widget allows the input of
 *   // several values, e.g checkboxes, select box...).
 *   // The sub-array is nested into a $langcode key where $langcode has the
 *   // same value of the $langcode parameter above.
 *   // The '#language' key holds the same value of $langcode and it is used
 *   // to access the field sub-array when $langcode is unknown.
 *   'field_foo' => array(
 *     '#tree' => TRUE,
614
 *     '#field_name' => The name of the field,
615 616
 *     '#language' => $langcode,
 *     $langcode => array(
617 618 619 620 621 622 623 624
 *       '#field_name' => The name of the field,
 *       '#language' => $langcode,
 *       '#field_parents' => The 'parents' space for the field in the form,
 *          equal to the #parents property of the $form parameter received by
 *          field_attach_form(),
 *       '#required' => Whether or not the field is required,
 *       '#title' => The label of the field instance,
 *       '#description' => The description text for the field instance,
625 626 627
 *
 *       // Only for 'single' widgets:
 *       '#theme' => 'field_multiple_value_form',
628
 *       '#cardinality' => The field cardinality,
629 630
 *       // One sub-array per copy of the widget, keyed by delta.
 *       0 => array(
631 632 633 634 635 636 637 638 639
 *         '#entity_type' => The name of the entity type,
 *         '#bundle' => The name of the bundle,
 *         '#field_name' => The name of the field,
 *         '#field_parents' => The 'parents' space for the field in the form,
 *            equal to the #parents property of the $form parameter received by
 *            field_attach_form(),
 *         '#title' => The title to be displayed by the widget,
 *         '#default_value' => The field value for delta 0,
 *         '#required' => Whether the widget should be marked required,
640
 *         '#delta' => 0,
641
 *         '#columns' => The array of field columns,
642
 *         // The remaining elements in the sub-array depend on the widget.
643
 *         '#type' => The type of the widget,
644 645 646 647 648 649 650
 *         ...
 *       ),
 *       1 => array(
 *         ...
 *       ),
 *
 *       // Only for multiple widgets:
651
 *       '#entity_type' => The name of the entity type,
652 653 654
 *       '#bundle' => $instance['bundle'],
 *       '#columns'  => array_keys($field['columns']),
 *       // The remaining elements in the sub-array depend on the widget.
655
 *       '#type' => The type of the widget,
656 657 658 659 660 661 662
 *       ...
 *     ),
 *     ...
 *   ),
 * )
 * @endcode
 *
663 664
 * Additionally, some processing data is placed in $form_state, and can be
 * accessed by field_form_get_state() and field_form_set_state().
665
 *
666 667
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
668
 * @param Drupal\Core\Entity\EntityInterface $entity
669
 *   The entity for which to load form elements, used to initialize
670 671
 *   default form values.
 * @param $form
672 673 674 675 676
 *   The form structure to fill in. This can be a full form structure, or a
 *   sub-element of a larger form. The #parents property can be set to control
 *   the location of submitted field values within $form_state['values']. If
 *   not specified, $form['#parents'] is set to an empty array, placing field
 *   values at the top-level of $form_state['values'].
677 678
 * @param $form_state
 *   An associative array containing the current state of the form.
679 680 681
 * @param $langcode
 *   The language the field values are going to be entered, if no language
 *   is provided the default site language will be used.
682 683 684
 *
 * @see field_form_get_state()
 * @see field_form_set_state()
685
 */
686
function field_attach_form($entity_type, EntityInterface $entity, &$form, &$form_state, $langcode = NULL) {
687 688 689
  // Set #parents to 'top-level' by default.
  $form += array('#parents' => array());

690
  // If no language is provided use the default site language.
691
  $options = array('langcode' => field_valid_language($langcode));
692
  $form += (array) field_invoke_method('form', _field_invoke_widget_target(), $entity, $form, $form_state, $options);
693

694
  // Add custom weight handling.
695 696
  $form['#pre_render'][] = '_field_extra_fields_pre_render';
  $form['#entity_type'] = $entity_type;
697
  $form['#bundle'] = $entity->bundle();
698

699
  // Let other modules make changes to the form.
700
  // Avoid module_invoke_all() to let parameters be taken by reference.
701 702
  foreach (module_implements('field_attach_form') as $module) {
    $function = $module . '_field_attach_form';
703
    $function($entity_type, $entity, $form, $form_state, $langcode);
704 705 706 707
  }
}

/**
708 709 710 711
 * Loads fields for the current revisions of a group of entities.
 *
 * Loads all fields for each entity object in a group of a single entity type.
 * The loaded field values are added directly to the entity objects.
712
 *
713 714 715 716
 * field_attach_load() is automatically called by the default entity controller
 * class, and thus, in most cases, doesn't need to be explicitly called by the
 * entity type module.
 *
717
 * @param $entity_type
718
 *   The type of entities in $entities; e.g., 'node' or 'user'.
719
 * @param $entities
720 721 722 723
 *   An array of entities for which to load fields, keyed by entity ID. Each
 *   entity needs to have its 'bundle', 'id' and (if applicable) 'revision' keys
 *   filled in. The function adds the loaded field data directly in the entity
 *   objects of the $entities array.
724
 * @param $age
725 726 727 728
 *   FIELD_LOAD_CURRENT to load the most recent revision for all fields, or
 *   FIELD_LOAD_REVISION to load the version indicated by each entity. Defaults
 *   to FIELD_LOAD_CURRENT; use field_attach_load_revision() instead of passing
 *   FIELD_LOAD_REVISION.
729 730
 * @param $options
 *   An associative array of additional options, with the following keys:
731 732 733 734 735 736
 *   - field_id: The field ID that should be loaded, instead of loading all
 *     fields, for each entity. Note that returned entities may contain data for
 *     other fields, for example if they are read from a cache.
 *   - deleted: If TRUE, the function will operate on deleted fields as well as
 *     non-deleted fields. If unset or FALSE, only non-deleted fields are
 *     operated on.
737
 */
738
function field_attach_load($entity_type, $entities, $age = FIELD_LOAD_CURRENT, $options = array()) {
739
  $field_info = field_info_field_by_ids();
740
  $load_current = $age == FIELD_LOAD_CURRENT;
741

742 743 744 745 746 747
  // Merge default options.
  $default_options = array(
    'deleted' => FALSE,
  );
  $options += $default_options;

748
  $info = entity_get_info($entity_type);
749 750 751
  // Only the most current revision of non-deleted fields for cacheable entity
  // types can be cached.
  $cache_read = $load_current && $info['field cache'] && empty($options['deleted']);
752
  // In addition, do not write to the cache when loading a single field.
753
  $cache_write = $cache_read && !isset($options['field_id']);
754

755
  if (empty($entities)) {
756 757 758
    return;
  }

759
  // Assume all entities will need to be queried. Entities found in the cache
760
  // will be removed from the list.
761
  $queried_entities = $entities;
762

763
  // Fetch available entities from cache, if applicable.
764
  if ($cache_read) {
765 766
    // Build the list of cache entries to retrieve.
    $cids = array();
767 768
    foreach ($entities as $id => $entity) {
      $cids[] = "field:$entity_type:$id";
769
    }
770
    $cache = cache('field')->getMultiple($cids);
771 772
    // Put the cached field values back into the entities and remove them from
    // the list of entities to query.
773 774
    foreach ($entities as $id => $entity) {
      $cid = "field:$entity_type:$id";
775
      if (isset($cache[$cid])) {
776
        unset($queried_entities[$id]);
777
        foreach ($cache[$cid]->data as $field_name => $values) {
778
          $entity->$field_name = $values;
779 780
        }
      }
781
    }
782 783
  }

784 785
  // Fetch other entities from their storage location.
  if ($queried_entities) {
786
    // The invoke order is:
787
    // - hook_field_storage_pre_load()
788
    // - storage backend's hook_field_storage_load()
789
    // - field-type module's hook_field_load()
790 791
    // - hook_field_attach_load()

792
    // Invoke hook_field_storage_pre_load(): let any module load field
793 794
    // data before the storage engine, accumulating along the way.
    $skip_fields = array();
795 796
    foreach (module_implements('field_storage_pre_load') as $module) {
      $function = $module . '_field_storage_pre_load';
797
      $function($entity_type, $queried_entities, $age, $skip_fields, $options);
798 799
    }

800 801
    $instances = array();

802
    // Collect the storage backends used by the remaining fields in the entities.
803
    $storages = array();
804
    foreach ($queried_entities as $entity) {
805 806 807
      $instances = _field_invoke_get_instances($entity_type, $entity->bundle(), $options);
      $id = $entity->id();
      $vid = $entity->getRevisionId();
808
      foreach ($instances as $instance) {
809 810 811 812 813 814 815 816
        $field_name = $instance['field_name'];
        $field_id = $instance['field_id'];
        // Make sure all fields are present at least as empty arrays.
        if (!isset($queried_entities[$id]->{$field_name})) {
          $queried_entities[$id]->{$field_name} = array();
        }
        // Collect the storage backend if the field has not been loaded yet.
        if (!isset($skip_fields[$field_id])) {
817
          $field = $field_info[$field_id];
818
          $storages[$field['storage']['type']][$field_id][] = $load_current ? $id : $vid;
819 820 821 822 823 824 825
        }
      }
    }

    // Invoke hook_field_storage_load() on the relevant storage backends.
    foreach ($storages as $storage => $fields) {
      $storage_info = field_info_storage_types($storage);
826
      module_invoke($storage_info['module'], 'field_storage_load', $entity_type, $queried_entities, $age, $fields, $options);
827
    }
828

829
    // Invoke field-type module's hook_field_load().
830 831
    $null = NULL;
    _field_invoke_multiple('load', $entity_type, $queried_entities, $age, $null, $options);
832 833

    // Invoke hook_field_attach_load(): let other modules act on loading the
834 835
    // entitiy.
    module_invoke_all('field_attach_load', $entity_type, $queried_entities, $age, $options);
836

837
    // Build cache data.
838
    if ($cache_write) {
839
      foreach ($queried_entities as $id => $entity) {
840
        $data = array();
841
        $instances = field_info_instances($entity_type, $entity->bundle());
842
        foreach ($instances as $instance) {
843
          $data[$instance['field_name']] = $queried_entities[$id]->{$instance['field_name']};
844
        }
845
        $cid = "field:$entity_type:$id";
846
        cache('field')->set($cid, $data);
847 848 849 850 851 852
      }
    }
  }
}

/**
853
 * Loads all fields for previous versions of a group of entities.
854
 *
855 856
 * Loading different versions of the same entities is not supported, and should
 * be done by separate calls to the function.
857
 *
858 859 860 861
 * field_attach_load_revision() is automatically called by the default entity
 * controller class, and thus, in most cases, doesn't need to be explicitly
 * called by the entity type module.
 *
862
 * @param $entity_type
863
 *   The type of entities in $entities; e.g. 'node' or 'user'.
864
 * @param $entities
865
 *   An array of entities for which to load fields, keyed by entity ID. Each
866 867 868
 *   entity needs to have its 'bundle', 'id' and (if applicable) 'revision' keys
 *   filled. The function adds the loaded field data directly in the entity
 *   objects of the $entities array.
869
 * @param $options
870 871
 *   An associative array of additional options. See field_attach_load() for
 *   details.
872
 */
873 874
function field_attach_load_revision($entity_type, $entities, $options = array()) {
  return field_attach_load($entity_type, $entities, FIELD_LOAD_REVISION, $options);
875 876 877
}

/**
878
 * Performs field validation against the field data in an entity.
879
 *
880 881 882
 * This function does not perform field widget validation on form submissions.
 * It is intended to be called during API save operations. Use
 * field_attach_form_validate() to validate form submissions.
883
 *
884 885
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
886
 * @param Drupal\Core\Entity\EntityInterface $entity
887
 *   The entity with fields to validate.
888
 * @throws Drupal\field\FieldValidationException
889 890 891
 *   If validation errors are found, a FieldValidationException is thrown. The
 *   'errors' property contains the array of errors, keyed by field name,
 *   language and delta.
892
 */
893
function field_attach_validate($entity_type, $entity) {
894
  $errors = array();
895
  // Check generic, field-type-agnostic errors first.
896
  _field_invoke_default('validate', $entity_type, $entity, $errors);
897
  // Check field-type specific errors.
898
  _field_invoke('validate', $entity_type, $entity, $errors);
899

900
  // Let other modules validate the entity.
901
  // Avoid module_invoke_all() to let $errors be taken by reference.
902 903
  foreach (module_implements('field_attach_validate') as $module) {
    $function = $module . '_field_attach_validate';
904
    $function($entity_type, $entity, $errors);
905 906 907 908 909 910 911 912
  }

  if ($errors) {
    throw new FieldValidationException($errors);
  }
}

/**
913
 * Performs field validation against form-submitted field values.
914
 *
915 916 917 918 919
 * There are two levels of validation for fields in forms: widget validation and
 * and field validation.
 * - Widget validation steps are specific to a given widget's own form structure
 *   and UI metaphors. They are executed through FAPI's #element_validate
 *   property during normal form validation.
920
 * - Field validation steps are common to a given field type, independently of
921 922
 *   the specific widget being used in a given form. They are defined in the
 *   field type's implementation of hook_field_validate().
923
 *
924 925 926 927
 * This function performs field validation in the context of a form submission.
 * It converts field validation errors into form errors on the correct form
 * elements. Fieldable entity types should call this function during their own
 * form validation function.
928
 *
929 930
 * @param $entity_type
 *   The type of $entity; e.g. 'node' or 'user'.
931
 * @param Drupal\Core\Entity\EntityInterface $entity
932
 *   The entity being submitted. The 'bundle', 'id' and (if applicable)
933
 *   'revision' keys should be present. The actual field values will be read
934 935
 *   from $form_state['values'].
 * @param $form
936 937
 *   The form structure where field elements are attached to. This might be a
 *   full form structure, or a sub-element of a larger form.
938 939 940
 * @param $form_state
 *   An associative array containing the current state of the form.
 */
941
function field_attach_form_validate($entity_type, EntityInterface $entity, $form, &$form_state) {
942 943
  // Perform field_level validation.
  try {
944
    field_attach_validate($entity_type, $entity);
945 946 947 948
  }
  catch (FieldValidationException $e) {