field.api.php 16.6 KB
Newer Older
1 2 3
<?php

/**
4
 * @addtogroup hooks
5 6 7
 * @{
 */

8
use Drupal\Component\Utility\NestedArray;
9 10
use Drupal\field\FieldUpdateForbiddenException;

11
/**
12
 * Exposes "pseudo-field" components on fieldable entities.
13
 *
14
 * Field UI's "Manage fields" and "Manage display" pages let users re-order
15
 * fields, but also non-field components. For nodes, these include the title
16
 * and other elements exposed by modules through hook_form_alter().
17
 *
18 19
 * Fieldable entities or modules that want to have their components supported
 * should expose them using this hook. The user-defined settings (weight,
20 21
 * visible) are automatically applied on rendered forms and displayed entities
 * in a #pre_render callback added by field_attach_form() and
22
 * EntityViewBuilder::viewMultiple().
23 24
 *
 * @see hook_field_extra_fields_alter()
25
 *
26
 * @return array
27
 *   A nested array of 'pseudo-field' elements. Each list is nested within the
28
 *   following keys: entity type, bundle name, context (either 'form' or
29 30 31
 *   'display'). The keys are the name of the elements as appearing in the
 *   renderable array (either the entity form or the displayed entity). The
 *   value is an associative array:
32 33
 *   - label: The human readable name of the element. Make sure you sanitize
 *     this appropriately.
34
 *   - description: A short description of the element contents.
35
 *   - weight: The default weight of the element.
36 37
 *   - visible: (optional) The default visibility of the element. Defaults to
 *     TRUE.
38 39
 *   - edit: (optional) String containing markup (normally a link) used as the
 *     element's 'edit' operation in the administration interface. Only for
40
 *     'form' context.
41 42
 *   - delete: (optional) String containing markup (normally a link) used as the
 *     element's 'delete' operation in the administration interface. Only for
43
 *     'form' context.
44
 */
45
function hook_field_extra_fields() {
46
  $extra = array();
47
  $module_language_enabled = \Drupal::moduleHandler()->moduleExists('language');
48 49 50 51 52
  $description = t('Node module element');

  foreach (node_type_get_types() as $bundle) {
    if ($bundle->has_title) {
      $extra['node'][$bundle->type]['form']['title'] = array(
53
        'label' => check_plain($bundle->title_label),
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        'description' => $description,
        'weight' => -5,
      );
    }

    // Add also the 'language' select if Language module is enabled and the
    // bundle has multilingual support.
    // Visibility of the ordering of the language selector is the same as on the
    // node/add form.
    if ($module_language_enabled) {
      $configuration = language_get_default_configuration('node', $bundle->type);
      if ($configuration['language_show']) {
        $extra['node'][$bundle->type]['form']['language'] = array(
          'label' => t('Language'),
          'description' => $description,
          'weight' => 0,
        );
      }
    }
    $extra['node'][$bundle->type]['display']['language'] = array(
      'label' => t('Language'),
      'description' => $description,
      'weight' => 0,
      'visible' => FALSE,
    );
  }
80

81 82 83
  return $extra;
}

84 85 86 87 88 89 90 91 92
/**
 * Alter "pseudo-field" components on fieldable entities.
 *
 * @param $info
 *   The associative array of 'pseudo-field' components.
 *
 * @see hook_field_extra_fields()
 */
function hook_field_extra_fields_alter(&$info) {
93
  // Force node title to always be at the top of the list by default.
94
  foreach (node_type_get_types() as $bundle) {
95 96
    if (isset($info['node'][$bundle->type]['form']['title'])) {
      $info['node'][$bundle->type]['form']['title']['weight'] = -20;
97
    }
98 99 100
  }
}

101 102 103
/**
 * @defgroup field_types Field Types API
 * @{
104
 * Defines field, widget, display formatter, and storage types.
105
 *
106 107 108
 * In the Field API, each field has a type, which determines what kind of data
 * (integer, string, date, etc.) the field can hold, which settings it provides,
 * and so on. The data type(s) accepted by a field are defined in
109
 * hook_field_schema().
110 111
 *
 * The Field Types API also defines two kinds of pluggable handlers: widgets
112 113 114
 * and formatters. @link field_widget Widgets @endlink specify how the field
 * appears in edit forms, while @link field_formatter formatters @endlink
 * specify how the field appears in displayed entities.
115
 *
116 117
 * See @link field Field API @endlink for information about the other parts of
 * the Field API.
118 119 120
 */


121 122 123 124
/**
 * Perform alterations on Field API field types.
 *
 * @param $info
125 126
 *   Array of information on field types as collected by the "field type" plugin
 *   manager.
127 128 129 130
 */
function hook_field_info_alter(&$info) {
  // Add a setting to all field types.
  foreach ($info as $field_type => $field_type_info) {
131 132 133
    $info[$field_type]['settings'] += array(
      'mymodule_additional_setting' => 'default value',
    );
134 135 136 137 138 139 140 141
  }

  // Change the default widget for fields of type 'foo'.
  if (isset($info['foo'])) {
    $info['foo']['default widget'] = 'mymodule_widget';
  }
}

142
/**
143
 * @} End of "defgroup field_types".
144 145 146 147 148 149 150 151 152 153
 */

/**
 * @defgroup field_widget Field Widget API
 * @{
 * Define Field API widget types.
 *
 * Field API widgets specify how fields are displayed in edit forms. Fields of a
 * given @link field_types field type @endlink may be edited using more than one
 * widget. In this case, the Field UI module allows the site builder to choose
154 155 156
 * which widget to use.
 *
 * Widgets are Plugins managed by the
157
 * Drupal\Core\Field\WidgetPluginManager class. A widget is
158
 * implemented by providing a class that implements
159 160
 * Drupal\Core\Field\WidgetInterface (in most cases, by
 * subclassing Drupal\Core\Field\WidgetBase), and provides the
161
 * proper annotation block.
162
 *
163
 * Widgets are @link forms_api_reference.html Form API @endlink
164 165 166
 * elements with additional processing capabilities. The methods of the
 * WidgetInterface object are typically called by the Field Attach API during
 * the creation of the field form structure with field_attach_form().
167 168 169 170 171 172
 *
 * @see field
 * @see field_types
 * @see field_formatter
 */

173 174 175
/**
 * Perform alterations on Field API widget types.
 *
176 177 178
 * @param array $info
 *   An array of informations on existing widget types, as collected by the
 *   annotation discovery mechanism.
179
 */
180
function hook_field_widget_info_alter(array &$info) {
181 182 183 184 185 186
  // Add a setting to a widget type.
  $info['text_textfield']['settings'] += array(
    'mymodule_additional_setting' => 'default value',
  );

  // Let a new field type re-use an existing widget.
187
  $info['options_select']['field_types'][] = 'my_field_type';
188 189
}

190 191 192 193 194 195 196 197
/**
 * Alter forms for field widgets provided by other modules.
 *
 * @param $element
 *   The field widget form element as constructed by hook_field_widget_form().
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $context
198
 *   An associative array containing the following key-value pairs:
199 200
 *   - form: The form structure to which widgets are being attached. This may be
 *     a full form structure, or a sub-element of a larger form.
201
 *   - widget: The widget plugin instance.
202
 *   - items: The field values, as a
203
 *     \Drupal\Core\Field\FieldItemListInterface object.
204
 *   - delta: The order of this item in the array of subelements (0, 1, 2, etc).
205 206
 *   - default: A boolean indicating whether the form is being shown as a dummy
 *     form to set default values.
207
 *
208
 * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
209
 * @see hook_field_widget_WIDGET_TYPE_form_alter()
210 211 212
 */
function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
213
  $field_definition = $context['items']->getFieldDefinition();
214
  if ($field_definition->getType() == 'mytype') {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

/**
 * Alter widget forms for a specific widget provided by another module.
 *
 * Modules can implement hook_field_widget_WIDGET_TYPE_form_alter() to modify a
 * specific widget form, rather than using hook_field_widget_form_alter() and
 * checking the widget type.
 *
 * @param $element
 *   The field widget form element as constructed by hook_field_widget_form().
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $context
232 233
 *   An associative array. See hook_field_widget_form_alter() for the structure
 *   and content of the array.
234
 *
235
 * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
236 237 238 239 240 241
 * @see hook_field_widget_form_alter()
 */
function hook_field_widget_WIDGET_TYPE_form_alter(&$element, &$form_state, $context) {
  // Code here will only act on widgets of type WIDGET_TYPE.  For example,
  // hook_field_widget_mymodule_autocomplete_form_alter() will only act on
  // widgets of type 'mymodule_autocomplete'.
242
  $element['#autocomplete_route_name'] = 'mymodule.autocomplete_route';
243 244
}

245
/**
246
 * @} End of "defgroup field_widget".
247 248 249 250 251 252 253 254 255 256 257 258
 */


/**
 * @defgroup field_formatter Field Formatter API
 * @{
 * Define Field API formatter types.
 *
 * Field API formatters specify how fields are displayed when the entity to
 * which the field is attached is displayed. Fields of a given
 * @link field_types field type @endlink may be displayed using more than one
 * formatter. In this case, the Field UI module allows the site builder to
259 260 261
 * choose which formatter to use.
 *
 * Formatters are Plugins managed by the
262
 * Drupal\Core\Field\FormatterPluginManager class. A formatter
263
 * is implemented by providing a class that implements
264 265
 * Drupal\Core\Field\FormatterInterface (in most cases, by
 * subclassing Drupal\Core\Field\FormatterBase), and provides
266
 * the proper annotation block.
267 268 269 270 271 272
 *
 * @see field
 * @see field_types
 * @see field_widget
 */

273 274 275
/**
 * Perform alterations on Field API formatter types.
 *
276 277 278
 * @param array $info
 *   An array of informations on existing formatter types, as collected by the
 *   annotation discovery mechanism.
279
 */
280
function hook_field_formatter_info_alter(array &$info) {
281 282 283 284 285 286 287 288 289
  // Add a setting to a formatter type.
  $info['text_default']['settings'] += array(
    'mymodule_additional_setting' => 'default value',
  );

  // Let a new field type re-use an existing formatter.
  $info['text_default']['field types'][] = 'my_field_type';
}

290
/**
291
 * @} End of "defgroup field_formatter".
292 293 294
 */

/**
295
 * @addtogroup field_attach
296 297 298 299
 * @{
 */

/**
300
 * Act on field_attach_form().
301
 *
302
 * This hook is invoked after the field module has performed the operation.
303
 * Implementing modules should alter the $form or $form_state parameters.
304
 *
305
 * @param \Drupal\Core\Entity\EntityInterface $entity
306
 *   The entity for which an edit form is being built.
307
 * @param $form
308 309 310 311
 *   The form structure field elements are attached to. This might be a full
 *   form structure, or a sub-element of a larger form. The $form['#parents']
 *   property can be used to identify the corresponding part of
 *   $form_state['values']. Hook implementations that need to act on the
312 313 314
 *   top-level properties of the global form (like #submit, #validate...) can
 *   add a #process callback to the array received in the $form parameter, and
 *   act on the $complete_form parameter in the process callback.
315 316 317
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $langcode
318 319
 *   The language the field values are going to be entered in. If no language is
 *   provided the default site language will be used.
320
 *
321 322
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use the entity system instead, see https://drupal.org/developing/api/entity
323
 */
324
function hook_field_attach_form(\Drupal\Core\Entity\EntityInterface $entity, &$form, &$form_state, $langcode) {
325
  // Add a checkbox allowing a given field to be emptied.
326 327
  // See hook_field_attach_extract_form_values() for the corresponding
  // processing code.
328 329 330 331
  $form['empty_field_foo'] = array(
    '#type' => 'checkbox',
    '#title' => t("Empty the 'field_foo' field"),
  );
332 333 334
}

/**
335
 * Act on field_attach_extract_form_values().
336
 *
337
 * This hook is invoked after the field module has performed the operation.
338
 *
339
 * @param \Drupal\Core\Entity\EntityInterface $entity
340 341 342
 *   The entity for which an edit form is being submitted. The incoming form
 *   values have been extracted as field values of the $entity object.
 * @param $form
343 344
 *   The form structure field elements are attached to. This might be a full
 *   form structure, or a sub-part of a larger form. The $form['#parents']
345 346 347 348
 *   property can be used to identify the corresponding part of
 *   $form_state['values'].
 * @param $form_state
 *   An associative array containing the current state of the form.
349
 *
350 351
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use the entity system instead, see https://drupal.org/developing/api/entity
352
 */
353
function hook_field_attach_extract_form_values(\Drupal\Core\Entity\EntityInterface $entity, $form, &$form_state) {
354 355
  // Sample case of an 'Empty the field' checkbox added on the form, allowing
  // a given field to be emptied.
356
  $values = NestedArray::getValue($form_state['values'], $form['#parents']);
357 358 359
  if (!empty($values['empty_field_foo'])) {
    unset($entity->field_foo);
  }
360 361 362
}

/**
363
 * @} End of "addtogroup field_attach".
364 365
 */

366 367 368 369 370 371
/**
 * Returns the maximum weight for the entity components handled by the module.
 *
 * Field API takes care of fields and 'extra_fields'. This hook is intended for
 * third-party modules adding other entity components (e.g. field_group).
 *
372
 * @param string $entity_type
373
 *   The type of entity; e.g. 'node' or 'user'.
374
 * @param string $bundle
375
 *   The bundle name.
376 377 378 379 380 381 382
 * @param string $context
 *   The context for which the maximum weight is requested. Either 'form' or
 *   'display'.
 * @param string $context_mode
 *   The view or form mode name.
 *
 * @return int
383 384 385
 *   The maximum weight of the entity's components, or NULL if no components
 *   were found.
 */
386
function hook_field_info_max_weight($entity_type, $bundle, $context, $context_mode) {
387 388
  $weights = array();

389
  foreach (my_module_entity_additions($entity_type, $bundle, $context, $context_mode) as $addition) {
390 391 392 393 394 395
    $weights[] = $addition['weight'];
  }

  return $weights ? max($weights) : NULL;
}

396
/**
397
 * @addtogroup field_crud
398 399 400
 * @{
 */

401 402 403 404 405 406 407 408 409 410
/**
 * Forbid a field update from occurring.
 *
 * Any module may forbid any update for any reason. For example, the
 * field's storage module might forbid an update if it would change
 * the storage schema while data for the field exists. A field type
 * module might forbid an update if it would change existing data's
 * semantics, or if there are external dependencies on field settings
 * that cannot be updated.
 *
411 412
 * To forbid the update from occurring, throw a
 * Drupal\field\FieldUpdateForbiddenException.
413
 *
414 415 416 417 418
 * @param $field
 *   The field as it will be post-update.
 * @param $prior_field
 *   The field as it is pre-update.
 */
419
function hook_field_update_forbid($field, $prior_field) {
420 421
  // A 'list' field stores integer keys mapped to display values. If
  // the new field will have fewer values, and any data exists for the
422
  // abandoned keys, the field will have no way to display them. So,
423
  // forbid such an update.
424
  if ($field->hasData() && count($field['settings']['allowed_values']) < count($prior_field['settings']['allowed_values'])) {
425 426 427
    // Identify the keys that will be lost.
    $lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($prior_field['settings']['allowed_values']));
    // If any data exist for those keys, forbid the update.
428
    $query = new EntityFieldQuery();
429 430 431 432 433
    $found = $query
      ->fieldCondition($prior_field['field_name'], 'value', $lost_keys)
      ->range(0, 1)
      ->execute();
    if ($found) {
434
      throw new FieldUpdateForbiddenException("Cannot update a list field not to include keys with existing data");
435 436 437 438
    }
  }
}

439 440 441
/**
 * Acts when a field record is being purged.
 *
442 443 444 445
 * In field_purge_field(), after the field definition has been removed from the
 * the system, the entity storage has purged stored field data, and the field
 * info cache has been cleared, this hook is invoked on all modules to allow
 * them to respond to the field being purged.
446 447 448 449 450 451 452 453 454 455 456 457 458
 *
 * @param $field
 *   The field being purged.
 */
function hook_field_purge_field($field) {
  db_delete('my_module_field_info')
    ->condition('id', $field['id'])
    ->execute();
}

/**
 * Acts when a field instance is being purged.
 *
459 460 461 462
 * In field_purge_instance(), after the instance definition has been removed
 * from the the system, the entity storage has purged stored field data, and the
 * field info cache has been cleared, this hook is invoked on all modules to
 * allow them to respond to the field instance being purged.
463 464 465 466
 *
 * @param $instance
 *   The instance being purged.
 */
467
function hook_field_purge_instance($instance) {
468 469 470 471 472
  db_delete('my_module_field_instance_info')
    ->condition('id', $instance['id'])
    ->execute();
}

473
/**
474
 * @} End of "addtogroup field_crud".
475 476
 */

477
/**
478
 * @} End of "addtogroup hooks".
479
 */