field.api.php 11.2 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
 * Field types are plugins annotated with class
21
 * \Drupal\Core\Field\Annotation\FieldType, and implement plugin interface
22 23 24 25 26 27 28
 * \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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
/**
 * Forbid a field storage 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.
 *
 * To forbid the update from occurring, throw a
 * \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException.
 *
 * @param \Drupal\field\FieldStorageConfigInterface $field_storage
 *   The field storage as it will be post-update.
 * @param \Drupal\field\FieldStorageConfigInterface $prior_field_storage
 *   The field storage as it is pre-update.
 *
 * @see entity_crud
 */
function hook_field_storage_config_update_forbid(\Drupal\field\FieldStorageConfigInterface $field_storage, \Drupal\field\FieldStorageConfigInterface $prior_field_storage) {
  // A 'list' field stores integer keys mapped to display values. If
  // the new field will have fewer values, and any data exists for the
  // abandoned keys, the field will have no way to display them. So,
  // forbid such an update.
  if ($field_storage->hasData() && count($field_storage['settings']['allowed_values']) < count($prior_field_storage['settings']['allowed_values'])) {
    // Identify the keys that will be lost.
    $lost_keys = array_diff(array_keys($field_storage['settings']['allowed_values']), array_keys($prior_field_storage['settings']['allowed_values']));
    // If any data exist for those keys, forbid the update.
    $query = new EntityFieldQuery();
    $found = $query
      ->fieldCondition($prior_field_storage['field_name'], 'value', $lost_keys)
      ->range(0, 1)
      ->execute();
    if ($found) {
      throw new \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException("Cannot update a list field storage not to include keys with existing data");
    }
  }
}

98
/**
99
 * @} End of "defgroup field_types".
100 101 102 103 104 105 106 107 108 109
 */

/**
 * @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
110 111 112
 * which widget to use.
 *
 * Widgets are Plugins managed by the
113
 * \Drupal\Core\Field\WidgetPluginManager class. A widget is a plugin annotated
114
 * with class \Drupal\Core\Field\Annotation\FieldWidget that implements
115 116 117
 * \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.
118
 *
119
 * Widgets are @link forms_api_reference.html Form API @endlink
120
 * elements with additional processing capabilities. The methods of the
121
 * WidgetInterface object are typically called by respective methods in the
122
 * \Drupal\Core\Entity\Entity\EntityFormDisplay class.
123 124 125 126
 *
 * @see field
 * @see field_types
 * @see field_formatter
127
 * @see plugin_api
128 129
 */

130 131 132
/**
 * Perform alterations on Field API widget types.
 *
133
 * @param array $info
134
 *   An array of information on existing widget types, as collected by the
135
 *   annotation discovery mechanism.
136
 */
137
function hook_field_widget_info_alter(array &$info) {
138
  // Let a new field type re-use an existing widget.
139
  $info['options_select']['field_types'][] = 'my_field_type';
140 141
}

142 143 144 145 146 147
/**
 * 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
148
 *   The current state of the form.
149
 * @param $context
150
 *   An associative array containing the following key-value pairs:
151 152
 *   - 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.
153
 *   - widget: The widget plugin instance.
154
 *   - items: The field values, as a
155
 *     \Drupal\Core\Field\FieldItemListInterface object.
156
 *   - delta: The order of this item in the array of subelements (0, 1, 2, etc).
157 158
 *   - default: A boolean indicating whether the form is being shown as a dummy
 *     form to set default values.
159
 *
160
 * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
161
 * @see hook_field_widget_WIDGET_TYPE_form_alter()
162
 */
163
function hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
164
  // Add a css class to widget form elements for all fields of type mytype.
165
  $field_definition = $context['items']->getFieldDefinition();
166
  if ($field_definition->getType() == 'mytype') {
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    // 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
182
 *   The current state of the form.
183
 * @param $context
184 185
 *   An associative array. See hook_field_widget_form_alter() for the structure
 *   and content of the array.
186
 *
187
 * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
188 189
 * @see hook_field_widget_form_alter()
 */
190
function hook_field_widget_WIDGET_TYPE_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
191 192 193
  // 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'.
194
  $element['#autocomplete_route_name'] = 'mymodule.autocomplete_route';
195 196
}

197
/**
198
 * @} End of "defgroup field_widget".
199 200 201 202 203 204 205 206 207 208 209 210
 */


/**
 * @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
211 212 213
 * choose which formatter to use.
 *
 * Formatters are Plugins managed by the
214
 * \Drupal\Core\Field\FormatterPluginManager class. A formatter is a plugin
215
 * annotated with class \Drupal\Core\Field\Annotation\FieldFormatter that
216 217 218
 * 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.
219 220 221 222
 *
 * @see field
 * @see field_types
 * @see field_widget
223
 * @see plugin_api
224 225
 */

226 227 228
/**
 * Perform alterations on Field API formatter types.
 *
229
 * @param array $info
230
 *   An array of information on existing formatter types, as collected by the
231
 *   annotation discovery mechanism.
232
 */
233
function hook_field_formatter_info_alter(array &$info) {
234 235 236 237
  // Let a new field type re-use an existing formatter.
  $info['text_default']['field types'][] = 'my_field_type';
}

238
/**
239
 * @} End of "defgroup field_formatter".
240 241
 */

242 243 244 245 246 247
/**
 * 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).
 *
248
 * @param string $entity_type
249
 *   The type of entity; e.g. 'node' or 'user'.
250
 * @param string $bundle
251
 *   The bundle name.
252 253 254 255 256 257 258
 * @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
259 260
 *   The maximum weight of the entity's components, or NULL if no components
 *   were found.
261 262
 *
 * @ingroup field_info
263
 */
264
function hook_field_info_max_weight($entity_type, $bundle, $context, $context_mode) {
265 266
  $weights = array();

267
  foreach (my_module_entity_additions($entity_type, $bundle, $context, $context_mode) as $addition) {
268 269 270 271 272 273
    $weights[] = $addition['weight'];
  }

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

274
/**
275
 * @addtogroup field_purge
276 277 278
 * @{
 */

279
/**
280
 * Acts when a field storage definition is being purged.
281
 *
282 283 284 285
 * In field_purge_field_storage(), after the storage definition has been removed
 * from the system, the entity storage has purged stored field data, and the
 * field definitions cache has been cleared, this hook is invoked on all modules
 * to allow them to respond to the field storage being purged.
286
 *
287 288
 * @param $field_storage \Drupal\field\Entity\FieldStorageConfig
 *   The field storage being purged.
289
 */
290 291 292
function hook_field_purge_field_storage(\Drupal\field\Entity\FieldStorageConfig $field_storage) {
  db_delete('my_module_field_storage_info')
    ->condition('uuid', $field_storage->uuid())
293 294 295 296
    ->execute();
}

/**
297
 * Acts when a field is being purged.
298
 *
299
 * In field_purge_field(), after the field definition has been removed
300 301
 * 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
302
 * allow them to respond to the field being purged.
303
 *
304 305
 * @param $field
 *   The field being purged.
306
 */
307 308 309
function hook_field_purge_field(\Drupal\field\Entity\FieldConfig $field) {
  db_delete('my_module_field_info')
    ->condition('id', $field->id())
310 311 312
    ->execute();
}

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

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