field.api.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. /**
  3. * @file
  4. * Field API documentation.
  5. */
  6. /**
  7. * @addtogroup hooks
  8. * @{
  9. */
  10. /**
  11. * @defgroup field_types Field Types API
  12. * @{
  13. * Defines field, widget, display formatter, and storage types.
  14. *
  15. * In the Field API, each field has a type, which determines what kind of data
  16. * (integer, string, date, etc.) the field can hold, which settings it provides,
  17. * and so on. The data type(s) accepted by a field are defined in the class
  18. * implementing \Drupal\Core\Field\FieldItemInterface::schema() method.
  19. *
  20. * Field types are plugins annotated with class
  21. * \Drupal\Core\Field\Annotation\FieldType, and implement plugin interface
  22. * \Drupal\Core\Field\FieldItemInterface. Field Type plugins are managed by the
  23. * \Drupal\Core\Field\FieldTypePluginManager class. Field type classes usually
  24. * extend base class \Drupal\Core\Field\FieldItemBase. Field-type plugins need
  25. * to be in the namespace \Drupal\{your_module}\Plugin\Field\FieldType. See the
  26. * @link plugin_api Plugin API topic @endlink for more information on how to
  27. * define plugins.
  28. *
  29. * The Field Types API also defines two kinds of pluggable handlers: widgets
  30. * and formatters. @link field_widget Widgets @endlink specify how the field
  31. * appears in edit forms, while @link field_formatter formatters @endlink
  32. * specify how the field appears in displayed entities.
  33. *
  34. * See @link field Field API @endlink for information about the other parts of
  35. * the Field API.
  36. *
  37. * @see field
  38. * @see field_widget
  39. * @see field_formatter
  40. * @see plugin_api
  41. */
  42. /**
  43. * Perform alterations on Field API field types.
  44. *
  45. * @param $info
  46. * Array of information on field types as collected by the "field type" plugin
  47. * manager.
  48. */
  49. function hook_field_info_alter(&$info) {
  50. // Change the default widget for fields of type 'foo'.
  51. if (isset($info['foo'])) {
  52. $info['foo']['default_widget'] = 'mymodule_widget';
  53. }
  54. }
  55. /**
  56. * Perform alterations on preconfigured field options.
  57. *
  58. * @param array $options
  59. * Array of options as returned from
  60. * \Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface::getPreconfiguredOptions().
  61. * @param string $field_type
  62. * The field type plugin ID.
  63. *
  64. * @see \Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface::getPreconfiguredOptions()
  65. */
  66. function hook_field_ui_preconfigured_options_alter(array &$options, $field_type) {
  67. // If the field is not an "entity_reference"-based field, bail out.
  68. /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
  69. $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
  70. $class = $field_type_manager->getPluginClass($field_type);
  71. if (!is_a($class, 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem', TRUE)) {
  72. return;
  73. }
  74. // Set the default formatter for media in entity reference fields to be the
  75. // "Rendered entity" formatter.
  76. if (!empty($options['media'])) {
  77. $options['media']['entity_view_display']['type'] = 'entity_reference_entity_view';
  78. }
  79. }
  80. /**
  81. * Forbid a field storage update from occurring.
  82. *
  83. * Any module may forbid any update for any reason. For example, the
  84. * field's storage module might forbid an update if it would change
  85. * the storage schema while data for the field exists. A field type
  86. * module might forbid an update if it would change existing data's
  87. * semantics, or if there are external dependencies on field settings
  88. * that cannot be updated.
  89. *
  90. * To forbid the update from occurring, throw a
  91. * \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException.
  92. *
  93. * @param \Drupal\field\FieldStorageConfigInterface $field_storage
  94. * The field storage as it will be post-update.
  95. * @param \Drupal\field\FieldStorageConfigInterface $prior_field_storage
  96. * The field storage as it is pre-update.
  97. *
  98. * @see entity_crud
  99. */
  100. function hook_field_storage_config_update_forbid(\Drupal\field\FieldStorageConfigInterface $field_storage, \Drupal\field\FieldStorageConfigInterface $prior_field_storage) {
  101. if ($field_storage->module == 'options' && $field_storage->hasData()) {
  102. // Forbid any update that removes allowed values with actual data.
  103. $allowed_values = $field_storage->getSetting('allowed_values');
  104. $prior_allowed_values = $prior_field_storage->getSetting('allowed_values');
  105. $lost_keys = array_keys(array_diff_key($prior_allowed_values, $allowed_values));
  106. if (_options_values_in_use($field_storage->getTargetEntityTypeId(), $field_storage->getName(), $lost_keys)) {
  107. throw new \Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException("A list field '{$field_storage->getName()}' with existing data cannot have its keys changed.");
  108. }
  109. }
  110. }
  111. /**
  112. * @} End of "defgroup field_types".
  113. */
  114. /**
  115. * @defgroup field_widget Field Widget API
  116. * @{
  117. * Define Field API widget types.
  118. *
  119. * Field API widgets specify how fields are displayed in edit forms. Fields of a
  120. * given @link field_types field type @endlink may be edited using more than one
  121. * widget. In this case, the Field UI module allows the site builder to choose
  122. * which widget to use.
  123. *
  124. * Widgets are Plugins managed by the
  125. * \Drupal\Core\Field\WidgetPluginManager class. A widget is a plugin annotated
  126. * with class \Drupal\Core\Field\Annotation\FieldWidget that implements
  127. * \Drupal\Core\Field\WidgetInterface (in most cases, by
  128. * subclassing \Drupal\Core\Field\WidgetBase). Widget plugins need to be in the
  129. * namespace \Drupal\{your_module}\Plugin\Field\FieldWidget.
  130. *
  131. * Widgets are @link form_api Form API @endlink elements with additional
  132. * processing capabilities. The methods of the WidgetInterface object are
  133. * typically called by respective methods in the
  134. * \Drupal\Core\Entity\Entity\EntityFormDisplay class.
  135. *
  136. * @see field
  137. * @see field_types
  138. * @see field_formatter
  139. * @see plugin_api
  140. */
  141. /**
  142. * Perform alterations on Field API widget types.
  143. *
  144. * @param array $info
  145. * An array of information on existing widget types, as collected by the
  146. * annotation discovery mechanism.
  147. */
  148. function hook_field_widget_info_alter(array &$info) {
  149. // Let a new field type re-use an existing widget.
  150. $info['options_select']['field_types'][] = 'my_field_type';
  151. }
  152. /**
  153. * Alter forms for field widgets provided by other modules.
  154. *
  155. * This hook can only modify individual elements within a field widget and
  156. * cannot alter the top level (parent element) for multi-value fields. In most
  157. * cases, you should use hook_field_widget_multivalue_form_alter() instead and
  158. * loop over the elements.
  159. *
  160. * @param $element
  161. * The field widget form element as constructed by
  162. * \Drupal\Core\Field\WidgetBaseInterface::form().
  163. * @param $form_state
  164. * The current state of the form.
  165. * @param $context
  166. * An associative array containing the following key-value pairs:
  167. * - form: The form structure to which widgets are being attached. This may be
  168. * a full form structure, or a sub-element of a larger form.
  169. * - widget: The widget plugin instance.
  170. * - items: The field values, as a
  171. * \Drupal\Core\Field\FieldItemListInterface object.
  172. * - delta: The order of this item in the array of subelements (0, 1, 2, etc).
  173. * - default: A boolean indicating whether the form is being shown as a dummy
  174. * form to set default values.
  175. *
  176. * @see \Drupal\Core\Field\WidgetBaseInterface::form()
  177. * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
  178. * @see hook_field_widget_WIDGET_TYPE_form_alter()
  179. * @see hook_field_widget_multivalue_form_alter()
  180. */
  181. function hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  182. // Add a css class to widget form elements for all fields of type mytype.
  183. $field_definition = $context['items']->getFieldDefinition();
  184. if ($field_definition->getType() == 'mytype') {
  185. // Be sure not to overwrite existing attributes.
  186. $element['#attributes']['class'][] = 'myclass';
  187. }
  188. }
  189. /**
  190. * Alter widget forms for a specific widget provided by another module.
  191. *
  192. * Modules can implement hook_field_widget_WIDGET_TYPE_form_alter() to modify a
  193. * specific widget form, rather than using hook_field_widget_form_alter() and
  194. * checking the widget type.
  195. *
  196. * This hook can only modify individual elements within a field widget and
  197. * cannot alter the top level (parent element) for multi-value fields. In most
  198. * cases, you should use hook_field_widget_multivalue_WIDGET_TYPE_form_alter()
  199. * instead and loop over the elements.
  200. *
  201. * @param $element
  202. * The field widget form element as constructed by
  203. * \Drupal\Core\Field\WidgetBaseInterface::form().
  204. * @param $form_state
  205. * The current state of the form.
  206. * @param $context
  207. * An associative array. See hook_field_widget_form_alter() for the structure
  208. * and content of the array.
  209. *
  210. * @see \Drupal\Core\Field\WidgetBaseInterface::form()
  211. * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
  212. * @see hook_field_widget_form_alter()
  213. * @see hook_field_widget_multivalue_WIDGET_TYPE_form_alter()
  214. */
  215. function hook_field_widget_WIDGET_TYPE_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  216. // Code here will only act on widgets of type WIDGET_TYPE. For example,
  217. // hook_field_widget_mymodule_autocomplete_form_alter() will only act on
  218. // widgets of type 'mymodule_autocomplete'.
  219. $element['#autocomplete_route_name'] = 'mymodule.autocomplete_route';
  220. }
  221. /**
  222. * Alter forms for multi-value field widgets provided by other modules.
  223. *
  224. * To alter the individual elements within the widget, loop over
  225. * \Drupal\Core\Render\Element::children($elements).
  226. *
  227. * @param array $elements
  228. * The field widget form elements as constructed by
  229. * \Drupal\Core\Field\WidgetBase::formMultipleElements().
  230. * @param \Drupal\Core\Form\FormStateInterface $form_state
  231. * The current state of the form.
  232. * @param array $context
  233. * An associative array containing the following key-value pairs:
  234. * - form: The form structure to which widgets are being attached. This may be
  235. * a full form structure, or a sub-element of a larger form.
  236. * - widget: The widget plugin instance.
  237. * - items: The field values, as a
  238. * \Drupal\Core\Field\FieldItemListInterface object.
  239. * - default: A boolean indicating whether the form is being shown as a dummy
  240. * form to set default values.
  241. *
  242. * @see \Drupal\Core\Field\WidgetBaseInterface::form()
  243. * @see \Drupal\Core\Field\WidgetBase::formMultipleElements()
  244. * @see hook_field_widget_multivalue_WIDGET_TYPE_form_alter()
  245. */
  246. function hook_field_widget_multivalue_form_alter(array &$elements, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  247. // Add a css class to widget form elements for all fields of type mytype.
  248. $field_definition = $context['items']->getFieldDefinition();
  249. if ($field_definition->getType() == 'mytype') {
  250. // Be sure not to overwrite existing attributes.
  251. $elements['#attributes']['class'][] = 'myclass';
  252. }
  253. }
  254. /**
  255. * Alter multi-value widget forms for a widget provided by another module.
  256. *
  257. * Modules can implement hook_field_widget_multivalue_WIDGET_TYPE_form_alter() to
  258. * modify a specific widget form, rather than using
  259. * hook_field_widget_form_alter() and checking the widget type.
  260. *
  261. * To alter the individual elements within the widget, loop over
  262. * \Drupal\Core\Render\Element::children($elements).
  263. *
  264. * @param array $elements
  265. * The field widget form elements as constructed by
  266. * \Drupal\Core\Field\WidgetBase::formMultipleElements().
  267. * @param \Drupal\Core\Form\FormStateInterface $form_state
  268. * The current state of the form.
  269. * @param array $context
  270. * An associative array. See hook_field_widget_multivalue_form_alter() for
  271. * the structure and content of the array.
  272. *
  273. * @see \Drupal\Core\Field\WidgetBaseInterface::form()
  274. * @see \Drupal\Core\Field\WidgetBase::formMultipleElements()
  275. * @see hook_field_widget_multivalue_form_alter()
  276. */
  277. function hook_field_widget_multivalue_WIDGET_TYPE_form_alter(array &$elements, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  278. // Code here will only act on widgets of type WIDGET_TYPE. For example,
  279. // hook_field_widget_multivalue_mymodule_autocomplete_form_alter() will only
  280. // act on widgets of type 'mymodule_autocomplete'.
  281. // Change the autocomplete route for each autocomplete element within the
  282. // multivalue widget.
  283. foreach (Element::children($elements) as $delta => $element) {
  284. $elements[$delta]['#autocomplete_route_name'] = 'mymodule.autocomplete_route';
  285. }
  286. }
  287. /**
  288. * @} End of "defgroup field_widget".
  289. */
  290. /**
  291. * @defgroup field_formatter Field Formatter API
  292. * @{
  293. * Define Field API formatter types.
  294. *
  295. * Field API formatters specify how fields are displayed when the entity to
  296. * which the field is attached is displayed. Fields of a given
  297. * @link field_types field type @endlink may be displayed using more than one
  298. * formatter. In this case, the Field UI module allows the site builder to
  299. * choose which formatter to use.
  300. *
  301. * Formatters are Plugins managed by the
  302. * \Drupal\Core\Field\FormatterPluginManager class. A formatter is a plugin
  303. * annotated with class \Drupal\Core\Field\Annotation\FieldFormatter that
  304. * implements \Drupal\Core\Field\FormatterInterface (in most cases, by
  305. * subclassing \Drupal\Core\Field\FormatterBase). Formatter plugins need to be
  306. * in the namespace \Drupal\{your_module}\Plugin\Field\FieldFormatter.
  307. *
  308. * @see field
  309. * @see field_types
  310. * @see field_widget
  311. * @see plugin_api
  312. */
  313. /**
  314. * Perform alterations on Field API formatter types.
  315. *
  316. * @param array $info
  317. * An array of information on existing formatter types, as collected by the
  318. * annotation discovery mechanism.
  319. */
  320. function hook_field_formatter_info_alter(array &$info) {
  321. // Let a new field type re-use an existing formatter.
  322. $info['text_default']['field_types'][] = 'my_field_type';
  323. }
  324. /**
  325. * @} End of "defgroup field_formatter".
  326. */
  327. /**
  328. * Returns the maximum weight for the entity components handled by the module.
  329. *
  330. * Field API takes care of fields and 'extra_fields'. This hook is intended for
  331. * third-party modules adding other entity components (e.g. field_group).
  332. *
  333. * @param string $entity_type
  334. * The type of entity; e.g. 'node' or 'user'.
  335. * @param string $bundle
  336. * The bundle name.
  337. * @param string $context
  338. * The context for which the maximum weight is requested. Either 'form' or
  339. * 'display'.
  340. * @param string $context_mode
  341. * The view or form mode name.
  342. *
  343. * @return int
  344. * The maximum weight of the entity's components, or NULL if no components
  345. * were found.
  346. *
  347. * @ingroup field_info
  348. */
  349. function hook_field_info_max_weight($entity_type, $bundle, $context, $context_mode) {
  350. $weights = [];
  351. foreach (my_module_entity_additions($entity_type, $bundle, $context, $context_mode) as $addition) {
  352. $weights[] = $addition['weight'];
  353. }
  354. return $weights ? max($weights) : NULL;
  355. }
  356. /**
  357. * @addtogroup field_purge
  358. * @{
  359. */
  360. /**
  361. * Acts when a field storage definition is being purged.
  362. *
  363. * In field_purge_field_storage(), after the storage definition has been removed
  364. * from the system, the entity storage has purged stored field data, and the
  365. * field definitions cache has been cleared, this hook is invoked on all modules
  366. * to allow them to respond to the field storage being purged.
  367. *
  368. * @param $field_storage \Drupal\field\Entity\FieldStorageConfig
  369. * The field storage being purged.
  370. */
  371. function hook_field_purge_field_storage(\Drupal\field\Entity\FieldStorageConfig $field_storage) {
  372. \Drupal::database()->delete('my_module_field_storage_info')
  373. ->condition('uuid', $field_storage->uuid())
  374. ->execute();
  375. }
  376. /**
  377. * Acts when a field is being purged.
  378. *
  379. * In field_purge_field(), after the field definition has been removed
  380. * from the system, the entity storage has purged stored field data, and the
  381. * field info cache has been cleared, this hook is invoked on all modules to
  382. * allow them to respond to the field being purged.
  383. *
  384. * @param $field
  385. * The field being purged.
  386. */
  387. function hook_field_purge_field(\Drupal\field\Entity\FieldConfig $field) {
  388. \Drupal::database()->delete('my_module_field_info')
  389. ->condition('id', $field->id())
  390. ->execute();
  391. }
  392. /**
  393. * @} End of "addtogroup field_purge".
  394. */
  395. /**
  396. * @} End of "addtogroup hooks".
  397. */