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

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

8
use Drupal\Component\Utility\NestedArray;
9

10 11 12
/**
 * @defgroup field_types Field Types API
 * @{
13
 * Defines field, widget, display formatter, and storage types.
14
 *
15 16 17
 * 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
18
 * hook_field_schema().
19
 *
20 21 22 23 24 25 26 27 28
 * Field types are plugins annotated with class
 * \Drupal\Core\Entity\Annotation\FieldType, and implement plugin interface
 * \Drupal\Core\Field\FieldItemInterface. Field Type plugins are managed by the
 * \Drupal\Core\Field\FieldTypePluginManager class. Field type classes usually
 * extend base class \Drupal\Core\Field\FieldItemBase. Field-type plugins need
 * to be in the namespace \Drupal\{your_module}\Plugin\Field\FieldType. See the
 * @link plugin_api Plugin API topic @endlink for more information on how to
 * define plugins.
 *
29
 * The Field Types API also defines two kinds of pluggable handlers: widgets
30 31 32
 * 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.
33
 *
34 35
 * See @link field Field API @endlink for information about the other parts of
 * the Field API.
36 37 38 39 40
 *
 * @see field
 * @see field_widget
 * @see field_formatter
 * @see plugin_api
41 42 43
 */


44 45 46 47
/**
 * Perform alterations on Field API field types.
 *
 * @param $info
48 49
 *   Array of information on field types as collected by the "field type" plugin
 *   manager.
50 51 52 53 54 55 56 57
 */
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';
  }
}

58
/**
59
 * @} End of "defgroup field_types".
60 61 62 63 64 65 66 67 68 69
 */

/**
 * @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
70 71 72
 * which widget to use.
 *
 * Widgets are Plugins managed by the
73 74 75 76 77
 * \Drupal\Core\Field\WidgetPluginManager class. A widget is a plugin annotated
 * with class \Drupal\Core\Entity\Annotation\FieldWidget that implements
 * \Drupal\Core\Field\WidgetInterface (in most cases, by
 * subclassing \Drupal\Core\Field\WidgetBase). Widget plugins need to be in the
 * namespace \Drupal\{your_module}\Plugin\Field\FieldWidget.
78
 *
79
 * Widgets are @link forms_api_reference.html Form API @endlink
80
 * elements with additional processing capabilities. The methods of the
81 82
 * WidgetInterface object are typically called by respective methods in the
 * \Drupal\entity\Entity\EntityFormDisplay class.
83 84 85 86
 *
 * @see field
 * @see field_types
 * @see field_formatter
87
 * @see plugin_api
88 89
 */

90 91 92
/**
 * Perform alterations on Field API widget types.
 *
93
 * @param array $info
94
 *   An array of information on existing widget types, as collected by the
95
 *   annotation discovery mechanism.
96
 */
97
function hook_field_widget_info_alter(array &$info) {
98
  // Let a new field type re-use an existing widget.
99
  $info['options_select']['field_types'][] = 'my_field_type';
100 101
}

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

157
/**
158
 * @} End of "defgroup field_widget".
159 160 161 162 163 164 165 166 167 168 169 170
 */


/**
 * @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
171 172 173
 * choose which formatter to use.
 *
 * Formatters are Plugins managed by the
174 175 176 177 178
 * \Drupal\Core\Field\FormatterPluginManager class. A formatter is a plugin
 * annotated with class \Drupal\Core\Entity\Annotation\FieldFormatter that
 * implements \Drupal\Core\Field\FormatterInterface (in most cases, by
 * subclassing \Drupal\Core\Field\FormatterBase). Formatter plugins need to be
 * in the namespace \Drupal\{your_module}\Plugin\Field\FieldFormatter.
179 180 181 182
 *
 * @see field
 * @see field_types
 * @see field_widget
183
 * @see plugin_api
184 185
 */

186 187 188
/**
 * Perform alterations on Field API formatter types.
 *
189
 * @param array $info
190
 *   An array of information on existing formatter types, as collected by the
191
 *   annotation discovery mechanism.
192
 */
193
function hook_field_formatter_info_alter(array &$info) {
194 195 196 197
  // Let a new field type re-use an existing formatter.
  $info['text_default']['field types'][] = 'my_field_type';
}

198
/**
199
 * @} End of "defgroup field_formatter".
200 201
 */

202 203 204 205 206 207
/**
 * 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).
 *
208
 * @param string $entity_type
209
 *   The type of entity; e.g. 'node' or 'user'.
210
 * @param string $bundle
211
 *   The bundle name.
212 213 214 215 216 217 218
 * @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
219 220
 *   The maximum weight of the entity's components, or NULL if no components
 *   were found.
221 222
 *
 * @ingroup field_info
223
 */
224
function hook_field_info_max_weight($entity_type, $bundle, $context, $context_mode) {
225 226
  $weights = array();

227
  foreach (my_module_entity_additions($entity_type, $bundle, $context, $context_mode) as $addition) {
228 229 230 231 232 233
    $weights[] = $addition['weight'];
  }

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

234
/**
235
 * @addtogroup field_purge
236 237 238
 * @{
 */

239 240 241 242 243 244 245 246 247 248
/**
 * 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.
 *
249
 * To forbid the update from occurring, throw a
250
 * \Drupal\Core\Entity\Exception\StorageDefinitionUpdateForbiddenException.
251
 *
252
 * @param \Drupal\field\FieldConfigInterface $field
253
 *   The field as it will be post-update.
254
 * @param \Drupal\field\FieldConfigInterface $prior_field
255
 *   The field as it is pre-update.
256 257
 *
 * @see entity_crud
258
 */
259
function hook_field_config_update_forbid(\Drupal\field\FieldConfigInterface $field, \Drupal\field\FieldConfigInterface $prior_field) {
260 261
  // A 'list' field stores integer keys mapped to display values. If
  // the new field will have fewer values, and any data exists for the
262
  // abandoned keys, the field will have no way to display them. So,
263
  // forbid such an update.
264
  if ($field->hasData() && count($field['settings']['allowed_values']) < count($prior_field['settings']['allowed_values'])) {
265 266 267
    // 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.
268
    $query = new EntityFieldQuery();
269 270 271 272 273
    $found = $query
      ->fieldCondition($prior_field['field_name'], 'value', $lost_keys)
      ->range(0, 1)
      ->execute();
    if ($found) {
274
      throw new \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException("Cannot update a list field not to include keys with existing data");
275 276 277 278
    }
  }
}

279 280 281
/**
 * Acts when a field record is being purged.
 *
282 283 284 285
 * 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.
286 287 288 289 290 291 292 293 294 295 296 297 298
 *
 * @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.
 *
299 300 301 302
 * 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.
303 304 305 306
 *
 * @param $instance
 *   The instance being purged.
 */
307
function hook_field_purge_instance($instance) {
308 309 310 311 312
  db_delete('my_module_field_instance_info')
    ->condition('id', $instance['id'])
    ->execute();
}

313
/**
314
 * @} End of "addtogroup field_purge".
315 316
 */

317
/**
318
 * @} End of "addtogroup hooks".
319
 */