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

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

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

11 12 13
/**
 * @defgroup field_types Field Types API
 * @{
14
 * Defines field, widget, display formatter, and storage types.
15
 *
16 17 18
 * 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
19
 * hook_field_schema().
20 21
 *
 * The Field Types API also defines two kinds of pluggable handlers: widgets
22 23 24
 * 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.
25
 *
26 27
 * See @link field Field API @endlink for information about the other parts of
 * the Field API.
28 29 30
 */


31 32 33 34
/**
 * Perform alterations on Field API field types.
 *
 * @param $info
35 36
 *   Array of information on field types as collected by the "field type" plugin
 *   manager.
37 38 39 40 41 42 43 44
 */
function hook_field_info_alter(&$info) {
  // Change the default widget for fields of type 'foo'.
  if (isset($info['foo'])) {
    $info['foo']['default widget'] = 'mymodule_widget';
  }
}

45
/**
46
 * @} End of "defgroup field_types".
47 48 49 50 51 52 53 54 55 56
 */

/**
 * @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
57 58 59
 * which widget to use.
 *
 * Widgets are Plugins managed by the
60
 * Drupal\Core\Field\WidgetPluginManager class. A widget is
61
 * implemented by providing a class that implements
62 63
 * Drupal\Core\Field\WidgetInterface (in most cases, by
 * subclassing Drupal\Core\Field\WidgetBase), and provides the
64
 * proper annotation block.
65
 *
66
 * Widgets are @link forms_api_reference.html Form API @endlink
67
 * elements with additional processing capabilities. The methods of the
68 69
 * WidgetInterface object are typically called by respective methods in the
 * \Drupal\entity\Entity\EntityFormDisplay class.
70 71 72 73 74 75
 *
 * @see field
 * @see field_types
 * @see field_formatter
 */

76 77 78
/**
 * Perform alterations on Field API widget types.
 *
79
 * @param array $info
80
 *   An array of information on existing widget types, as collected by the
81
 *   annotation discovery mechanism.
82
 */
83
function hook_field_widget_info_alter(array &$info) {
84
  // Let a new field type re-use an existing widget.
85
  $info['options_select']['field_types'][] = 'my_field_type';
86 87
}

88 89 90 91 92 93 94 95
/**
 * 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
96
 *   An associative array containing the following key-value pairs:
97 98
 *   - 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.
99
 *   - widget: The widget plugin instance.
100
 *   - items: The field values, as a
101
 *     \Drupal\Core\Field\FieldItemListInterface object.
102
 *   - delta: The order of this item in the array of subelements (0, 1, 2, etc).
103 104
 *   - default: A boolean indicating whether the form is being shown as a dummy
 *     form to set default values.
105
 *
106
 * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
107
 * @see hook_field_widget_WIDGET_TYPE_form_alter()
108 109 110
 */
function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
111
  $field_definition = $context['items']->getFieldDefinition();
112
  if ($field_definition->getType() == 'mytype') {
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    // 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
130 131
 *   An associative array. See hook_field_widget_form_alter() for the structure
 *   and content of the array.
132
 *
133
 * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
134 135 136 137 138 139
 * @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'.
140
  $element['#autocomplete_route_name'] = 'mymodule.autocomplete_route';
141 142
}

143
/**
144
 * @} End of "defgroup field_widget".
145 146 147 148 149 150 151 152 153 154 155 156
 */


/**
 * @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
157 158 159
 * choose which formatter to use.
 *
 * Formatters are Plugins managed by the
160
 * Drupal\Core\Field\FormatterPluginManager class. A formatter
161
 * is implemented by providing a class that implements
162 163
 * Drupal\Core\Field\FormatterInterface (in most cases, by
 * subclassing Drupal\Core\Field\FormatterBase), and provides
164
 * the proper annotation block.
165 166 167 168 169 170
 *
 * @see field
 * @see field_types
 * @see field_widget
 */

171 172 173
/**
 * Perform alterations on Field API formatter types.
 *
174
 * @param array $info
175
 *   An array of information on existing formatter types, as collected by the
176
 *   annotation discovery mechanism.
177
 */
178
function hook_field_formatter_info_alter(array &$info) {
179 180 181 182
  // Let a new field type re-use an existing formatter.
  $info['text_default']['field types'][] = 'my_field_type';
}

183
/**
184
 * @} End of "defgroup field_formatter".
185 186
 */

187 188 189 190 191 192
/**
 * 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).
 *
193
 * @param string $entity_type
194
 *   The type of entity; e.g. 'node' or 'user'.
195
 * @param string $bundle
196
 *   The bundle name.
197 198 199 200 201 202 203
 * @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
204 205
 *   The maximum weight of the entity's components, or NULL if no components
 *   were found.
206 207
 *
 * @ingroup field_info
208
 */
209
function hook_field_info_max_weight($entity_type, $bundle, $context, $context_mode) {
210 211
  $weights = array();

212
  foreach (my_module_entity_additions($entity_type, $bundle, $context, $context_mode) as $addition) {
213 214 215 216 217 218
    $weights[] = $addition['weight'];
  }

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

219
/**
220
 * @addtogroup field_crud
221 222 223
 * @{
 */

224 225 226 227 228 229 230 231 232 233
/**
 * 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.
 *
234
 * To forbid the update from occurring, throw a
235
 * Drupal\field\FieldConfigUpdateForbiddenException.
236
 *
237
 * @param \Drupal\field\FieldConfigInterface $field
238
 *   The field as it will be post-update.
239
 * @param \Drupal\field\FieldConfigInterface $prior_field
240 241
 *   The field as it is pre-update.
 */
242
function hook_field_config_update_forbid(\Drupal\field\FieldConfigInterface $field, \Drupal\field\FieldConfigInterface $prior_field) {
243 244
  // A 'list' field stores integer keys mapped to display values. If
  // the new field will have fewer values, and any data exists for the
245
  // abandoned keys, the field will have no way to display them. So,
246
  // forbid such an update.
247
  if ($field->hasData() && count($field['settings']['allowed_values']) < count($prior_field['settings']['allowed_values'])) {
248 249 250
    // 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.
251
    $query = new EntityFieldQuery();
252 253 254 255 256
    $found = $query
      ->fieldCondition($prior_field['field_name'], 'value', $lost_keys)
      ->range(0, 1)
      ->execute();
    if ($found) {
257
      throw new FieldConfigUpdateForbiddenException("Cannot update a list field not to include keys with existing data");
258 259 260 261
    }
  }
}

262 263 264
/**
 * Acts when a field record is being purged.
 *
265 266 267 268
 * 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.
269 270 271 272 273 274 275 276 277 278 279 280 281
 *
 * @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.
 *
282 283 284 285
 * 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.
286 287 288 289
 *
 * @param $instance
 *   The instance being purged.
 */
290
function hook_field_purge_instance($instance) {
291 292 293 294 295
  db_delete('my_module_field_instance_info')
    ->condition('id', $instance['id'])
    ->execute();
}

296
/**
297
 * @} End of "addtogroup field_crud".
298 299
 */

300
/**
301
 * @} End of "addtogroup hooks".
302
 */