field.api.php

  1. drupal
    1. 7 modules/field/field.api.php
    2. 8 core/modules/field/field.api.php

Functions & methods

NameDescription
hook_field_accessDetermine whether the user has access to a given field.
hook_field_attach_create_bundleAct on field_attach_create_bundle().
hook_field_attach_deleteAct on field_attach_delete().
hook_field_attach_delete_bundleAct on field_attach_delete_bundle.
hook_field_attach_delete_revisionAct on field_attach_delete_revision().
hook_field_attach_formAct on field_attach_form().
hook_field_attach_insertAct on field_attach_insert().
hook_field_attach_loadAct on field_attach_load().
hook_field_attach_prepare_translation_alterPerform alterations on field_attach_prepare_translation().
hook_field_attach_preprocess_alterAlter field_attach_preprocess() variables.
hook_field_attach_presaveAct on field_attach_presave().
hook_field_attach_purgeAct on field_purge_data().
hook_field_attach_rename_bundleAct on field_attach_rename_bundle().
hook_field_attach_submitAct on field_attach_submit().
hook_field_attach_updateAct on field_attach_update().
hook_field_attach_validateAct on field_attach_validate().
hook_field_attach_view_alterPerform alterations on field_attach_view() or field_view_field().
hook_field_available_languages_alterAlter field_available_languages() values.
hook_field_create_fieldAct on a field being created.
hook_field_create_instanceAct on a field instance being created.
hook_field_deleteDefine custom delete behavior for this module's field data.
hook_field_delete_fieldAct on a field being deleted.
hook_field_delete_instanceAct on a field instance being deleted.
hook_field_delete_revisionDefine custom revision delete behavior for this module's field types.
hook_field_display_alterAlters the display settings of a field before it gets displayed.
hook_field_display_ENTITY_TYPE_alterAlters the display settings of a field on a given entity type before it gets displayed.
hook_field_extra_fieldsExposes "pseudo-field" components on fieldable entities.
hook_field_extra_fields_alterAlter "pseudo-field" components on fieldable entities.
hook_field_extra_fields_display_alterAlters the display settings of pseudo-fields before an entity is displayed.
hook_field_formatter_infoExpose Field API formatter types.
hook_field_formatter_info_alterPerform alterations on Field API formatter types.
hook_field_formatter_prepare_viewAllow formatters to load information for field values being displayed.
hook_field_formatter_viewBuild a renderable array for a field value.
hook_field_infoDefine Field API field types.
hook_field_info_alterPerform alterations on Field API field types.
hook_field_info_max_weightReturns the maximum weight for the entity components handled by the module.
hook_field_insertDefine custom insert behavior for this module's field data.
hook_field_is_emptyDefine what constitutes an empty item for a field type.
hook_field_language_alterPerform alterations on field_language() values.
hook_field_loadDefine custom load behavior for this module's field types.
hook_field_prepare_translationDefine custom prepare_translation behavior for this module's field types.
hook_field_prepare_viewPrepare field values prior to display.
hook_field_presaveDefine custom presave behavior for this module's field types.
hook_field_purge_fieldActs when a field record is being purged.
hook_field_purge_instanceActs when a field instance is being purged.
hook_field_read_fieldAct on field records being read from the database.
hook_field_read_instanceAct on a field record being read from the database.
hook_field_schemaDefine the Field API schema for a field structure.
hook_field_storage_create_fieldAct on creation of a new field.
hook_field_storage_deleteDelete all field data for an entity.
hook_field_storage_delete_fieldAct on deletion of a field.
hook_field_storage_delete_instanceAct on deletion of a field instance.
hook_field_storage_delete_revisionDelete a single revision of field data for an entity.
hook_field_storage_detailsReveal the internal details about the storage for a field.
hook_field_storage_details_alterPerform alterations on Field API storage details.
hook_field_storage_infoExpose Field API storage backends.
hook_field_storage_info_alterPerform alterations on Field API storage types.
hook_field_storage_loadLoad field data for a set of entities.
hook_field_storage_pre_insertAct before the storage backends insert field data.
hook_field_storage_pre_loadAct before the storage backends load field data.
hook_field_storage_pre_updateAct before the storage backends update field data.
hook_field_storage_purgeRemove field storage information when field data is purged.
hook_field_storage_purge_fieldRemove field storage information when a field record is purged.
hook_field_storage_purge_field_instanceRemove field storage information when a field instance is purged.
hook_field_storage_queryExecute an EntityFieldQuery.
hook_field_storage_update_fieldUpdate the storage information for a field.
hook_field_storage_writeWrite field data for an entity.
hook_field_updateDefine custom update behavior for this module's field data.
hook_field_update_fieldAct on a field being updated.
hook_field_update_forbidForbid a field update from occurring.
hook_field_update_instanceAct on a field instance being updated.
hook_field_validateValidate this module's field data.
hook_field_widget_errorFlag a field-level validation error.
hook_field_widget_formReturn the form for a single field widget.
hook_field_widget_form_alterAlter forms for field widgets provided by other modules.
hook_field_widget_infoExpose Field API widget types.
hook_field_widget_info_alterPerform alterations on Field API widget types.
hook_field_widget_properties_alterAlters the widget properties of a field instance before it gets displayed.
hook_field_widget_properties_ENTITY_TYPE_alterAlters the widget properties of a field instance on a given entity type before it gets displayed.
hook_field_widget_WIDGET_TYPE_form_alterAlter widget forms for a specific widget provided by another module.

File

modules/field/field.api.php
View source
  1. <?php
  2. /**
  3. * @addtogroup hooks
  4. * @{
  5. */
  6. /**
  7. * Exposes "pseudo-field" components on fieldable entities.
  8. *
  9. * Field UI's "Manage fields" and "Manage display" pages let users re-order
  10. * fields, but also non-field components. For nodes, these include the title,
  11. * poll choices, and other elements exposed by modules through hook_form() or
  12. * hook_form_alter().
  13. *
  14. * Fieldable entities or modules that want to have their components supported
  15. * should expose them using this hook. The user-defined settings (weight,
  16. * visible) are automatically applied on rendered forms and displayed
  17. * entities in a #pre_render callback added by field_attach_form() and
  18. * field_attach_view().
  19. *
  20. * @see _field_extra_fields_pre_render()
  21. * @see hook_field_extra_fields_alter()
  22. *
  23. * @return
  24. * A nested array of 'pseudo-field' components. Each list is nested within
  25. * the following keys: entity type, bundle name, context (either 'form' or
  26. * 'display'). The keys are the name of the elements as appearing in the
  27. * renderable array (either the entity form or the displayed entity). The
  28. * value is an associative array:
  29. * - label: The human readable name of the component.
  30. * - description: A short description of the component contents.
  31. * - weight: The default weight of the element.
  32. */
  33. function hook_field_extra_fields() {
  34. $extra['node']['poll'] = array(
  35. 'form' => array(
  36. 'choice_wrapper' => array(
  37. 'label' => t('Poll choices'),
  38. 'description' => t('Poll choices'),
  39. 'weight' => -4,
  40. ),
  41. 'settings' => array(
  42. 'label' => t('Poll settings'),
  43. 'description' => t('Poll module settings'),
  44. 'weight' => -3,
  45. ),
  46. ),
  47. 'display' => array(
  48. 'poll_view_voting' => array(
  49. 'label' => t('Poll vote'),
  50. 'description' => t('Poll vote'),
  51. 'weight' => 0,
  52. ),
  53. 'poll_view_results' => array(
  54. 'label' => t('Poll results'),
  55. 'description' => t('Poll results'),
  56. 'weight' => 0,
  57. ),
  58. )
  59. );
  60. return $extra;
  61. }
  62. /**
  63. * Alter "pseudo-field" components on fieldable entities.
  64. *
  65. * @param $info
  66. * The associative array of 'pseudo-field' components.
  67. *
  68. * @see hook_field_extra_fields()
  69. */
  70. function hook_field_extra_fields_alter(&$info) {
  71. // Force node title to always be at the top of the list by default.
  72. foreach (node_type_get_types() as $bundle) {
  73. if (isset($info['node'][$bundle->type]['form']['title'])) {
  74. $info['node'][$bundle->type]['form']['title']['weight'] = -20;
  75. }
  76. }
  77. }
  78. /**
  79. * @defgroup field_types Field Types API
  80. * @{
  81. * Define field types.
  82. *
  83. * In the Field API, each field has a type, which determines what kind of data
  84. * (integer, string, date, etc.) the field can hold, which settings it provides,
  85. * and so on. The data type(s) accepted by a field are defined in
  86. * hook_field_schema(); other basic properties of a field are defined in
  87. * hook_field_info(). The other hooks below are called by the Field Attach API
  88. * to perform field-type-specific actions.
  89. *
  90. * The Field Types API also defines two kinds of pluggable handlers: widgets
  91. * and formatters. @link field_widget Widgets @endlink specify how the field
  92. * appears in edit forms, while @link field_formatter formatters @endlink
  93. * specify how the field appears in displayed entities.
  94. *
  95. * A third kind of pluggable handlers, storage backends, is defined by the
  96. * @link field_storage Field Storage API @endlink.
  97. *
  98. * See @link field Field API @endlink for information about the other parts of
  99. * the Field API.
  100. */
  101. /**
  102. * Define Field API field types.
  103. *
  104. * @return
  105. * An array whose keys are field type names and whose values are arrays
  106. * describing the field type, with the following key/value pairs:
  107. * - label: The human-readable name of the field type.
  108. * - description: A short description for the field type.
  109. * - settings: An array whose keys are the names of the settings available
  110. * for the field type, and whose values are the default values for those
  111. * settings.
  112. * - instance_settings: An array whose keys are the names of the settings
  113. * available for instances of the field type, and whose values are the
  114. * default values for those settings. Instance-level settings can have
  115. * different values on each field instance, and thus allow greater
  116. * flexibility than field-level settings. It is recommended to put settings
  117. * at the instance level whenever possible. Notable exceptions: settings
  118. * acting on the schema definition, or settings that Views needs to use
  119. * across field instances (for example, the list of allowed values).
  120. * - default_widget: The machine name of the default widget to be used by
  121. * instances of this field type, when no widget is specified in the
  122. * instance definition. This widget must be available whenever the field
  123. * type is available (i.e. provided by the field type module, or by a module
  124. * the field type module depends on).
  125. * - default_formatter: The machine name of the default formatter to be used
  126. * by instances of this field type, when no formatter is specified in the
  127. * instance definition. This formatter must be available whenever the field
  128. * type is available (i.e. provided by the field type module, or by a module
  129. * the field type module depends on).
  130. * - no_ui: (optional) A boolean specifying that users should not be allowed
  131. * to create fields and instances of this field type through the UI. Such
  132. * fields can only be created programmatically with field_create_field()
  133. * and field_create_instance(). Defaults to FALSE.
  134. *
  135. * @see hook_field_info_alter()
  136. */
  137. function hook_field_info() {
  138. return array(
  139. 'text' => array(
  140. 'label' => t('Text'),
  141. 'description' => t('This field stores varchar text in the database.'),
  142. 'settings' => array('max_length' => 255),
  143. 'instance_settings' => array('text_processing' => 0),
  144. 'default_widget' => 'text_textfield',
  145. 'default_formatter' => 'text_default',
  146. ),
  147. 'text_long' => array(
  148. 'label' => t('Long text'),
  149. 'description' => t('This field stores long text in the database.'),
  150. 'settings' => array('max_length' => ''),
  151. 'instance_settings' => array('text_processing' => 0),
  152. 'default_widget' => 'text_textarea',
  153. 'default_formatter' => 'text_default',
  154. ),
  155. 'text_with_summary' => array(
  156. 'label' => t('Long text and summary'),
  157. 'description' => t('This field stores long text in the database along with optional summary text.'),
  158. 'settings' => array('max_length' => ''),
  159. 'instance_settings' => array('text_processing' => 1, 'display_summary' => 0),
  160. 'default_widget' => 'text_textarea_with_summary',
  161. 'default_formatter' => 'text_summary_or_trimmed',
  162. ),
  163. );
  164. }
  165. /**
  166. * Perform alterations on Field API field types.
  167. *
  168. * @param $info
  169. * Array of information on field types exposed by hook_field_info()
  170. * implementations.
  171. */
  172. function hook_field_info_alter(&$info) {
  173. // Add a setting to all field types.
  174. foreach ($info as $field_type => $field_type_info) {
  175. $info[$field_type]['settings'] += array(
  176. 'mymodule_additional_setting' => 'default value',
  177. );
  178. }
  179. // Change the default widget for fields of type 'foo'.
  180. if (isset($info['foo'])) {
  181. $info['foo']['default widget'] = 'mymodule_widget';
  182. }
  183. }
  184. /**
  185. * Define the Field API schema for a field structure.
  186. *
  187. * This hook MUST be defined in .install for it to be detected during
  188. * installation and upgrade.
  189. *
  190. * @param $field
  191. * A field structure.
  192. *
  193. * @return
  194. * An associative array with the following keys:
  195. * - columns: An array of Schema API column specifications, keyed by column
  196. * name. This specifies what comprises a value for a given field. For
  197. * example, a value for a number field is simply 'value', while a value for
  198. * a formatted text field is the combination of 'value' and 'format'. It is
  199. * recommended to avoid having the column definitions depend on field
  200. * settings when possible. No assumptions should be made on how storage
  201. * engines internally use the original column name to structure their
  202. * storage.
  203. * - indexes: (optional) An array of Schema API indexes definitions. Only
  204. * columns that appear in the 'columns' array are allowed. Those indexes
  205. * will be used as default indexes. Callers of field_create_field() can
  206. * specify additional indexes, or, at their own risk, modify the default
  207. * indexes specified by the field-type module. Some storage engines might
  208. * not support indexes.
  209. * - foreign keys: (optional) An array of Schema API foreign keys
  210. * definitions.
  211. */
  212. function hook_field_schema($field) {
  213. if ($field['type'] == 'text_long') {
  214. $columns = array(
  215. 'value' => array(
  216. 'type' => 'text',
  217. 'size' => 'big',
  218. 'not null' => FALSE,
  219. ),
  220. );
  221. }
  222. else {
  223. $columns = array(
  224. 'value' => array(
  225. 'type' => 'varchar',
  226. 'length' => $field['settings']['max_length'],
  227. 'not null' => FALSE,
  228. ),
  229. );
  230. }
  231. $columns += array(
  232. 'format' => array(
  233. 'type' => 'varchar',
  234. 'length' => 255,
  235. 'not null' => FALSE,
  236. ),
  237. );
  238. return array(
  239. 'columns' => $columns,
  240. 'indexes' => array(
  241. 'format' => array('format'),
  242. ),
  243. 'foreign keys' => array(
  244. 'format' => array(
  245. 'table' => 'filter_format',
  246. 'columns' => array('format' => 'format'),
  247. ),
  248. ),
  249. );
  250. }
  251. /**
  252. * Define custom load behavior for this module's field types.
  253. *
  254. * Unlike most other field hooks, this hook operates on multiple entities. The
  255. * $entities, $instances and $items parameters are arrays keyed by entity ID.
  256. * For performance reasons, information for all available entity should be
  257. * loaded in a single query where possible.
  258. *
  259. * Note that the changes made to the field values get cached by the field cache
  260. * for subsequent loads. You should never use this hook to load fieldable
  261. * entities, since this is likely to cause infinite recursions when
  262. * hook_field_load() is run on those as well. Use
  263. * hook_field_formatter_prepare_view() instead.
  264. *
  265. * Make changes or additions to field values by altering the $items parameter by
  266. * reference. There is no return value.
  267. *
  268. * @param $entity_type
  269. * The type of $entity.
  270. * @param $entities
  271. * Array of entities being loaded, keyed by entity ID.
  272. * @param $field
  273. * The field structure for the operation.
  274. * @param $instances
  275. * Array of instance structures for $field for each entity, keyed by entity
  276. * ID.
  277. * @param $langcode
  278. * The language code associated with $items.
  279. * @param $items
  280. * Array of field values already loaded for the entities, keyed by entity ID.
  281. * Store your changes in this parameter (passed by reference).
  282. * @param $age
  283. * FIELD_LOAD_CURRENT to load the most recent revision for all fields, or
  284. * FIELD_LOAD_REVISION to load the version indicated by each entity.
  285. */
  286. function hook_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  287. // Sample code from text.module: precompute sanitized strings so they are
  288. // stored in the field cache.
  289. foreach ($entities as $id => $entity) {
  290. foreach ($items[$id] as $delta => $item) {
  291. // Only process items with a cacheable format, the rest will be handled
  292. // by formatters if needed.
  293. if (empty($instances[$id]['settings']['text_processing']) || filter_format_allowcache($item['format'])) {
  294. $items[$id][$delta]['safe_value'] = isset($item['value']) ? _text_sanitize($instances[$id], $langcode, $item, 'value') : '';
  295. if ($field['type'] == 'text_with_summary') {
  296. $items[$id][$delta]['safe_summary'] = isset($item['summary']) ? _text_sanitize($instances[$id], $langcode, $item, 'summary') : '';
  297. }
  298. }
  299. }
  300. }
  301. }
  302. /**
  303. * Prepare field values prior to display.
  304. *
  305. * This hook is invoked before the field values are handed to formatters
  306. * for display, and runs before the formatters' own
  307. * hook_field_formatter_prepare_view().
  308. *
  309. * Unlike most other field hooks, this hook operates on multiple entities. The
  310. * $entities, $instances and $items parameters are arrays keyed by entity ID.
  311. * For performance reasons, information for all available entities should be
  312. * loaded in a single query where possible.
  313. *
  314. * Make changes or additions to field values by altering the $items parameter by
  315. * reference. There is no return value.
  316. *
  317. * @param $entity_type
  318. * The type of $entity.
  319. * @param $entities
  320. * Array of entities being displayed, keyed by entity ID.
  321. * @param $field
  322. * The field structure for the operation.
  323. * @param $instances
  324. * Array of instance structures for $field for each entity, keyed by entity
  325. * ID.
  326. * @param $langcode
  327. * The language associated to $items.
  328. * @param $items
  329. * $entity->{$field['field_name']}, or an empty array if unset.
  330. */
  331. function hook_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  332. // Sample code from image.module: if there are no images specified at all,
  333. // use the default image.
  334. foreach ($entities as $id => $entity) {
  335. if (empty($items[$id]) && $field['settings']['default_image']) {
  336. if ($file = file_load($field['settings']['default_image'])) {
  337. $items[$id][0] = (array) $file + array(
  338. 'is_default' => TRUE,
  339. 'alt' => '',
  340. 'title' => '',
  341. );
  342. }
  343. }
  344. }
  345. }
  346. /**
  347. * Validate this module's field data.
  348. *
  349. * If there are validation problems, add to the $errors array (passed by
  350. * reference). There is no return value.
  351. *
  352. * @param $entity_type
  353. * The type of $entity.
  354. * @param $entity
  355. * The entity for the operation.
  356. * @param $field
  357. * The field structure for the operation.
  358. * @param $instance
  359. * The instance structure for $field on $entity's bundle.
  360. * @param $langcode
  361. * The language associated with $items.
  362. * @param $items
  363. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  364. * @param $errors
  365. * The array of errors (keyed by field name, language code, and delta) that
  366. * have already been reported for the entity. The function should add its
  367. * errors to this array. Each error is an associative array with the following
  368. * keys and values:
  369. * - error: An error code (should be a string prefixed with the module name).
  370. * - message: The human readable message to be displayed.
  371. */
  372. function hook_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  373. foreach ($items as $delta => $item) {
  374. if (!empty($item['value'])) {
  375. if (!empty($field['settings']['max_length']) && drupal_strlen($item['value']) > $field['settings']['max_length']) {
  376. $errors[$field['field_name']][$langcode][$delta][] = array(
  377. 'error' => 'text_max_length',
  378. 'message' => t('%name: the value may not be longer than %max characters.', array('%name' => $instance['label'], '%max' => $field['settings']['max_length'])),
  379. );
  380. }
  381. }
  382. }
  383. }
  384. /**
  385. * Define custom presave behavior for this module's field types.
  386. *
  387. * Make changes or additions to field values by altering the $items parameter by
  388. * reference. There is no return value.
  389. *
  390. * @param $entity_type
  391. * The type of $entity.
  392. * @param $entity
  393. * The entity for the operation.
  394. * @param $field
  395. * The field structure for the operation.
  396. * @param $instance
  397. * The instance structure for $field on $entity's bundle.
  398. * @param $langcode
  399. * The language associated with $items.
  400. * @param $items
  401. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  402. */
  403. function hook_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  404. if ($field['type'] == 'number_decimal') {
  405. // Let PHP round the value to ensure consistent behavior across storage
  406. // backends.
  407. foreach ($items as $delta => $item) {
  408. if (isset($item['value'])) {
  409. $items[$delta]['value'] = round($item['value'], $field['settings']['scale']);
  410. }
  411. }
  412. }
  413. }
  414. /**
  415. * Define custom insert behavior for this module's field data.
  416. *
  417. * This hook is invoked from field_attach_insert() on the module that defines a
  418. * field, during the process of inserting an entity object (node, taxonomy term,
  419. * etc.). It is invoked just before the data for this field on the particular
  420. * entity object is inserted into field storage. Only field modules that are
  421. * storing or tracking information outside the standard field storage mechanism
  422. * need to implement this hook.
  423. *
  424. * @param $entity_type
  425. * The type of $entity.
  426. * @param $entity
  427. * The entity for the operation.
  428. * @param $field
  429. * The field structure for the operation.
  430. * @param $instance
  431. * The instance structure for $field on $entity's bundle.
  432. * @param $langcode
  433. * The language associated with $items.
  434. * @param $items
  435. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  436. *
  437. * @see hook_field_update()
  438. * @see hook_field_delete()
  439. */
  440. function hook_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  441. if (variable_get('taxonomy_maintain_index_table', TRUE) && $field['storage']['type'] == 'field_sql_storage' && $entity_type == 'node' && $entity->status) {
  442. $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created', ));
  443. foreach ($items as $item) {
  444. $query->values(array(
  445. 'nid' => $entity->nid,
  446. 'tid' => $item['tid'],
  447. 'sticky' => $entity->sticky,
  448. 'created' => $entity->created,
  449. ));
  450. }
  451. $query->execute();
  452. }
  453. }
  454. /**
  455. * Define custom update behavior for this module's field data.
  456. *
  457. * This hook is invoked from field_attach_update() on the module that defines a
  458. * field, during the process of updating an entity object (node, taxonomy term,
  459. * etc.). It is invoked just before the data for this field on the particular
  460. * entity object is updated into field storage. Only field modules that are
  461. * storing or tracking information outside the standard field storage mechanism
  462. * need to implement this hook.
  463. *
  464. * @param $entity_type
  465. * The type of $entity.
  466. * @param $entity
  467. * The entity for the operation.
  468. * @param $field
  469. * The field structure for the operation.
  470. * @param $instance
  471. * The instance structure for $field on $entity's bundle.
  472. * @param $langcode
  473. * The language associated with $items.
  474. * @param $items
  475. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  476. *
  477. * @see hook_field_insert()
  478. * @see hook_field_delete()
  479. */
  480. function hook_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  481. if (variable_get('taxonomy_maintain_index_table', TRUE) && $field['storage']['type'] == 'field_sql_storage' && $entity_type == 'node') {
  482. $first_call = &drupal_static(__FUNCTION__, array());
  483. // We don't maintain data for old revisions, so clear all previous values
  484. // from the table. Since this hook runs once per field, per object, make
  485. // sure we only wipe values once.
  486. if (!isset($first_call[$entity->nid])) {
  487. $first_call[$entity->nid] = FALSE;
  488. db_delete('taxonomy_index')->condition('nid', $entity->nid)->execute();
  489. }
  490. // Only save data to the table if the node is published.
  491. if ($entity->status) {
  492. $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
  493. foreach ($items as $item) {
  494. $query->values(array(
  495. 'nid' => $entity->nid,
  496. 'tid' => $item['tid'],
  497. 'sticky' => $entity->sticky,
  498. 'created' => $entity->created,
  499. ));
  500. }
  501. $query->execute();
  502. }
  503. }
  504. }
  505. /**
  506. * Update the storage information for a field.
  507. *
  508. * This is invoked on the field's storage module from field_update_field(),
  509. * before the new field information is saved to the database. The field storage
  510. * module should update its storage tables to agree with the new field
  511. * information. If there is a problem, the field storage module should throw an
  512. * exception.
  513. *
  514. * @param $field
  515. * The updated field structure to be saved.
  516. * @param $prior_field
  517. * The previously-saved field structure.
  518. * @param $has_data
  519. * TRUE if the field has data in storage currently.
  520. */
  521. function hook_field_storage_update_field($field, $prior_field, $has_data) {
  522. if (!$has_data) {
  523. // There is no data. Re-create the tables completely.
  524. $prior_schema = _field_sql_storage_schema($prior_field);
  525. foreach ($prior_schema as $name => $table) {
  526. db_drop_table($name, $table);
  527. }
  528. $schema = _field_sql_storage_schema($field);
  529. foreach ($schema as $name => $table) {
  530. db_create_table($name, $table);
  531. }
  532. }
  533. else {
  534. // There is data. See field_sql_storage_field_storage_update_field() for
  535. // an example of what to do to modify the schema in place, preserving the
  536. // old data as much as possible.
  537. }
  538. drupal_get_schema(NULL, TRUE);
  539. }
  540. /**
  541. * Define custom delete behavior for this module's field data.
  542. *
  543. * This hook is invoked from field_attach_delete() on the module that defines a
  544. * field, during the process of deleting an entity object (node, taxonomy term,
  545. * etc.). It is invoked just before the data for this field on the particular
  546. * entity object is deleted from field storage. Only field modules that are
  547. * storing or tracking information outside the standard field storage mechanism
  548. * need to implement this hook.
  549. *
  550. * @param $entity_type
  551. * The type of $entity.
  552. * @param $entity
  553. * The entity for the operation.
  554. * @param $field
  555. * The field structure for the operation.
  556. * @param $instance
  557. * The instance structure for $field on $entity's bundle.
  558. * @param $langcode
  559. * The language associated with $items.
  560. * @param $items
  561. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  562. *
  563. * @see hook_field_insert()
  564. * @see hook_field_update()
  565. */
  566. function hook_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
  567. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  568. foreach ($items as $delta => $item) {
  569. // For hook_file_references(), remember that this is being deleted.
  570. $item['file_field_name'] = $field['field_name'];
  571. // Pass in the ID of the object that is being removed so all references can
  572. // be counted in hook_file_references().
  573. $item['file_field_type'] = $entity_type;
  574. $item['file_field_id'] = $id;
  575. file_field_delete_file($item, $field, $entity_type, $id);
  576. }
  577. }
  578. /**
  579. * Define custom revision delete behavior for this module's field types.
  580. *
  581. * This hook is invoked just before the data is deleted from field storage
  582. * in field_attach_delete_revision(), and will only be called for fieldable
  583. * types that are versioned.
  584. *
  585. * @param $entity_type
  586. * The type of $entity.
  587. * @param $entity
  588. * The entity for the operation.
  589. * @param $field
  590. * The field structure for the operation.
  591. * @param $instance
  592. * The instance structure for $field on $entity's bundle.
  593. * @param $langcode
  594. * The language associated with $items.
  595. * @param $items
  596. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  597. */
  598. function hook_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
  599. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  600. foreach ($items as $delta => $item) {
  601. // For hook_file_references, remember that this file is being deleted.
  602. $item['file_field_name'] = $field['field_name'];
  603. if (file_field_delete_file($item, $field, $entity_type, $id)) {
  604. $items[$delta] = NULL;
  605. }
  606. }
  607. }
  608. /**
  609. * Define custom prepare_translation behavior for this module's field types.
  610. *
  611. * @param $entity_type
  612. * The type of $entity.
  613. * @param $entity
  614. * The entity for the operation.
  615. * @param $field
  616. * The field structure for the operation.
  617. * @param $instance
  618. * The instance structure for $field on $entity's bundle.
  619. * @param $langcode
  620. * The language associated to $items.
  621. * @param $items
  622. * $entity->{$field['field_name']}[$langcode], or an empty array if unset.
  623. * @param $source_entity
  624. * The source entity from which field values are being copied.
  625. * @param $source_langcode
  626. * The source language from which field values are being copied.
  627. */
  628. function hook_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) {
  629. // If the translating user is not permitted to use the assigned text format,
  630. // we must not expose the source values.
  631. $field_name = $field['field_name'];
  632. $formats = filter_formats();
  633. $format_id = $source_entity->{$field_name}[$source_langcode][0]['format'];
  634. if (!filter_access($formats[$format_id])) {
  635. $items = array();
  636. }
  637. }
  638. /**
  639. * Define what constitutes an empty item for a field type.
  640. *
  641. * @param $item
  642. * An item that may or may not be empty.
  643. * @param $field
  644. * The field to which $item belongs.
  645. *
  646. * @return
  647. * TRUE if $field's type considers $item not to contain any data;
  648. * FALSE otherwise.
  649. */
  650. function hook_field_is_empty($item, $field) {
  651. if (empty($item['value']) && (string) $item['value'] !== '0') {
  652. return TRUE;
  653. }
  654. return FALSE;
  655. }
  656. /**
  657. * @} End of "defgroup field_types"
  658. */
  659. /**
  660. * @defgroup field_widget Field Widget API
  661. * @{
  662. * Define Field API widget types.
  663. *
  664. * Field API widgets specify how fields are displayed in edit forms. Fields of a
  665. * given @link field_types field type @endlink may be edited using more than one
  666. * widget. In this case, the Field UI module allows the site builder to choose
  667. * which widget to use. Widget types are defined by implementing
  668. * hook_field_widget_info().
  669. *
  670. * Widgets are
  671. * @link http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html Form API @endlink
  672. * elements with additional processing capabilities. Widget hooks are typically
  673. * called by the Field Attach API during the creation of the field form
  674. * structure with field_attach_form().
  675. *
  676. * @see field
  677. * @see field_types
  678. * @see field_formatter
  679. */
  680. /**
  681. * Expose Field API widget types.
  682. *
  683. * @return
  684. * An array describing the widget types implemented by the module.
  685. * The keys are widget type names. To avoid name clashes, widget type
  686. * names should be prefixed with the name of the module that exposes them.
  687. * The values are arrays describing the widget type, with the following
  688. * key/value pairs:
  689. * - label: The human-readable name of the widget type.
  690. * - description: A short description for the widget type.
  691. * - field types: An array of field types the widget supports.
  692. * - settings: An array whose keys are the names of the settings available
  693. * for the widget type, and whose values are the default values for those
  694. * settings.
  695. * - behaviors: (optional) An array describing behaviors of the widget, with
  696. * the following elements:
  697. * - multiple values: One of the following constants:
  698. * - FIELD_BEHAVIOR_DEFAULT: (default) If the widget allows the input of
  699. * one single field value (most common case). The widget will be
  700. * repeated for each value input.
  701. * - FIELD_BEHAVIOR_CUSTOM: If one single copy of the widget can receive
  702. * several field values. Examples: checkboxes, multiple select,
  703. * comma-separated textfield.
  704. * - default value: One of the following constants:
  705. * - FIELD_BEHAVIOR_DEFAULT: (default) If the widget accepts default
  706. * values.
  707. * - FIELD_BEHAVIOR_NONE: if the widget does not support default values.
  708. *
  709. * @see hook_field_widget_info_alter()
  710. * @see hook_field_widget_form()
  711. * @see hook_field_widget_form_alter()
  712. * @see hook_field_widget_WIDGET_TYPE_form_alter()
  713. * @see hook_field_widget_error()
  714. * @see hook_field_widget_settings_form()
  715. */
  716. function hook_field_widget_info() {
  717. return array(
  718. 'text_textfield' => array(
  719. 'label' => t('Text field'),
  720. 'field types' => array('text'),
  721. 'settings' => array('size' => 60),
  722. 'behaviors' => array(
  723. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  724. 'default value' => FIELD_BEHAVIOR_DEFAULT,
  725. ),
  726. ),
  727. 'text_textarea' => array(
  728. 'label' => t('Text area (multiple rows)'),
  729. 'field types' => array('text_long'),
  730. 'settings' => array('rows' => 5),
  731. 'behaviors' => array(
  732. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  733. 'default value' => FIELD_BEHAVIOR_DEFAULT,
  734. ),
  735. ),
  736. 'text_textarea_with_summary' => array(
  737. 'label' => t('Text area with a summary'),
  738. 'field types' => array('text_with_summary'),
  739. 'settings' => array('rows' => 20, 'summary_rows' => 5),
  740. 'behaviors' => array(
  741. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  742. 'default value' => FIELD_BEHAVIOR_DEFAULT,
  743. ),
  744. ),
  745. );
  746. }
  747. /**
  748. * Perform alterations on Field API widget types.
  749. *
  750. * @param $info
  751. * Array of informations on widget types exposed by hook_field_widget_info()
  752. * implementations.
  753. */
  754. function hook_field_widget_info_alter(&$info) {
  755. // Add a setting to a widget type.
  756. $info['text_textfield']['settings'] += array(
  757. 'mymodule_additional_setting' => 'default value',
  758. );
  759. // Let a new field type re-use an existing widget.
  760. $info['options_select']['field types'][] = 'my_field_type';
  761. }
  762. /**
  763. * Return the form for a single field widget.
  764. *
  765. * Field widget form elements should be based on the passed-in $element, which
  766. * contains the base form element properties derived from the field
  767. * configuration.
  768. *
  769. * Field API will set the weight, field name and delta values for each form
  770. * element. If there are multiple values for this field, the Field API will
  771. * invoke this hook as many times as needed.
  772. *
  773. * Note that, depending on the context in which the widget is being included
  774. * (regular entity form, field configuration form, advanced search form...),
  775. * the values for $field and $instance might be different from the "official"
  776. * definitions returned by field_info_field() and field_info_instance().
  777. * Examples: mono-value widget even if the field is multi-valued, non-required
  778. * widget even if the field is 'required'...
  779. *
  780. * Therefore, the FAPI element callbacks (such as #process, #element_validate,
  781. * #value_callback...) used by the widget cannot use the field_info_field()
  782. * or field_info_instance() functions to retrieve the $field or $instance
  783. * definitions they should operate on. The field_widget_field() and
  784. * field_widget_instance() functions should be used instead to fetch the
  785. * current working definitions from $form_state, where Field API stores them.
  786. *
  787. * Alternatively, hook_field_widget_form() can extract the needed specific
  788. * properties from $field and $instance and set them as ad-hoc
  789. * $element['#custom'] properties, for later use by its element callbacks.
  790. *
  791. * Other modules may alter the form element provided by this function using
  792. * hook_field_widget_form_alter().
  793. *
  794. * @param $form
  795. * The form structure where widgets are being attached to. This might be a
  796. * full form structure, or a sub-element of a larger form.
  797. * @param $form_state
  798. * An associative array containing the current state of the form.
  799. * @param $field
  800. * The field structure.
  801. * @param $instance
  802. * The field instance.
  803. * @param $langcode
  804. * The language associated with $items.
  805. * @param $items
  806. * Array of default values for this field.
  807. * @param $delta
  808. * The order of this item in the array of subelements (0, 1, 2, etc).
  809. * @param $element
  810. * A form element array containing basic properties for the widget:
  811. * - #entity_type: The name of the entity the field is attached to.
  812. * - #bundle: The name of the field bundle the field is contained in.
  813. * - #field_name: The name of the field.
  814. * - #language: The language the field is being edited in.
  815. * - #field_parents: The 'parents' space for the field in the form. Most
  816. * widgets can simply overlook this property. This identifies the
  817. * location where the field values are placed within
  818. * $form_state['values'], and is used to access processing information
  819. * for the field through the field_form_get_state() and
  820. * field_form_set_state() functions.
  821. * - #columns: A list of field storage columns of the field.
  822. * - #title: The sanitized element label for the field instance, ready for
  823. * output.
  824. * - #description: The sanitized element description for the field instance,
  825. * ready for output.
  826. * - #required: A Boolean indicating whether the element value is required;
  827. * for required multiple value fields, only the first widget's values are
  828. * required.
  829. * - #delta: The order of this item in the array of subelements; see $delta
  830. * above.
  831. *
  832. * @return
  833. * The form elements for a single widget for this field.
  834. *
  835. * @see field_widget_field()
  836. * @see field_widget_instance()
  837. * @see hook_field_widget_form_alter()
  838. * @see hook_field_widget_WIDGET_TYPE_form_alter()
  839. */
  840. function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  841. $element += array(
  842. '#type' => $instance['widget']['type'],
  843. '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  844. );
  845. return $element;
  846. }
  847. /**
  848. * Alter forms for field widgets provided by other modules.
  849. *
  850. * @param $element
  851. * The field widget form element as constructed by hook_field_widget_form().
  852. * @param $form_state
  853. * An associative array containing the current state of the form.
  854. * @param $context
  855. * An associative array containing the following key-value pairs, matching the
  856. * arguments received by hook_field_widget_form():
  857. * - form: The form structure to which widgets are being attached. This may be
  858. * a full form structure, or a sub-element of a larger form.
  859. * - field: The field structure.
  860. * - instance: The field instance structure.
  861. * - langcode: The language associated with $items.
  862. * - items: Array of default values for this field.
  863. * - delta: The order of this item in the array of subelements (0, 1, 2, etc).
  864. *
  865. * @see hook_field_widget_form()
  866. * @see hook_field_widget_WIDGET_TYPE_form_alter()
  867. */
  868. function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  869. // Add a css class to widget form elements for all fields of type mytype.
  870. if ($context['field']['type'] == 'mytype') {
  871. // Be sure not to overwrite existing attributes.
  872. $element['#attributes']['class'][] = 'myclass';
  873. }
  874. }
  875. /**
  876. * Alter widget forms for a specific widget provided by another module.
  877. *
  878. * Modules can implement hook_field_widget_WIDGET_TYPE_form_alter() to modify a
  879. * specific widget form, rather than using hook_field_widget_form_alter() and
  880. * checking the widget type.
  881. *
  882. * @param $element
  883. * The field widget form element as constructed by hook_field_widget_form().
  884. * @param $form_state
  885. * An associative array containing the current state of the form.
  886. * @param $context
  887. * An associative array containing the following key-value pairs, matching the
  888. * arguments received by hook_field_widget_form():
  889. * - "form": The form structure where widgets are being attached to. This
  890. * might be a full form structure, or a sub-element of a larger form.
  891. * - "field": The field structure.
  892. * - "instance": The field instance structure.
  893. * - "langcode": The language associated with $items.
  894. * - "items": Array of default values for this field.
  895. * - "delta": The order of this item in the array of subelements (0, 1, 2,
  896. * etc).
  897. *
  898. * @see hook_field_widget_form()
  899. * @see hook_field_widget_form_alter()
  900. */
  901. function hook_field_widget_WIDGET_TYPE_form_alter(&$element, &$form_state, $context) {
  902. // Code here will only act on widgets of type WIDGET_TYPE. For example,
  903. // hook_field_widget_mymodule_autocomplete_form_alter() will only act on
  904. // widgets of type 'mymodule_autocomplete'.
  905. $element['#autocomplete_path'] = 'mymodule/autocomplete_path';
  906. }
  907. /**
  908. * Flag a field-level validation error.
  909. *
  910. * @param $element
  911. * An array containing the form element for the widget. The error needs to be
  912. * flagged on the right sub-element, according to the widget's internal
  913. * structure.
  914. * @param $error
  915. * An associative array with the following key-value pairs, as returned by
  916. * hook_field_validate():
  917. * - error: the error code. Complex widgets might need to report different
  918. * errors to different form elements inside the widget.
  919. * - message: the human readable message to be displayed.
  920. * @param $form
  921. * The form structure where field elements are attached to. This might be a
  922. * full form structure, or a sub-element of a larger form.
  923. * @param $form_state
  924. * An associative array containing the current state of the form.
  925. */
  926. function hook_field_widget_error($element, $error, $form, &$form_state) {
  927. form_error($element['value'], $error['message']);
  928. }
  929. /**
  930. * @} End of "defgroup field_widget"
  931. */
  932. /**
  933. * @defgroup field_formatter Field Formatter API
  934. * @{
  935. * Define Field API formatter types.
  936. *
  937. * Field API formatters specify how fields are displayed when the entity to
  938. * which the field is attached is displayed. Fields of a given
  939. * @link field_types field type @endlink may be displayed using more than one
  940. * formatter. In this case, the Field UI module allows the site builder to
  941. * choose which formatter to use. Field formatters are defined by implementing
  942. * hook_field_formatter_info().
  943. *
  944. * @see field
  945. * @see field_types
  946. * @see field_widget
  947. */
  948. /**
  949. * Expose Field API formatter types.
  950. *
  951. * Formatters handle the display of field values. Formatter hooks are typically
  952. * called by the Field Attach API field_attach_prepare_view() and
  953. * field_attach_view() functions.
  954. *
  955. * @return
  956. * An array describing the formatter types implemented by the module.
  957. * The keys are formatter type names. To avoid name clashes, formatter type
  958. * names should be prefixed with the name of the module that exposes them.
  959. * The values are arrays describing the formatter type, with the following
  960. * key/value pairs:
  961. * - label: The human-readable name of the formatter type.
  962. * - description: A short description for the formatter type.
  963. * - field types: An array of field types the formatter supports.
  964. * - settings: An array whose keys are the names of the settings available
  965. * for the formatter type, and whose values are the default values for
  966. * those settings.
  967. *
  968. * @see hook_field_formatter_info_alter()
  969. * @see hook_field_formatter_view()
  970. * @see hook_field_formatter_prepare_view()
  971. */
  972. function hook_field_formatter_info() {
  973. return array(
  974. 'text_default' => array(
  975. 'label' => t('Default'),
  976. 'field types' => array('text', 'text_long', 'text_with_summary'),
  977. ),
  978. 'text_plain' => array(
  979. 'label' => t('Plain text'),
  980. 'field types' => array('text', 'text_long', 'text_with_summary'),
  981. ),
  982. // The text_trimmed formatter displays the trimmed version of the
  983. // full element of the field. It is intended to be used with text
  984. // and text_long fields. It also works with text_with_summary
  985. // fields though the text_summary_or_trimmed formatter makes more
  986. // sense for that field type.
  987. 'text_trimmed' => array(
  988. 'label' => t('Trimmed'),
  989. 'field types' => array('text', 'text_long', 'text_with_summary'),
  990. ),
  991. // The 'summary or trimmed' field formatter for text_with_summary
  992. // fields displays returns the summary element of the field or, if
  993. // the summary is empty, the trimmed version of the full element
  994. // of the field.
  995. 'text_summary_or_trimmed' => array(
  996. 'label' => t('Summary or trimmed'),
  997. 'field types' => array('text_with_summary'),
  998. ),
  999. );
  1000. }
  1001. /**
  1002. * Perform alterations on Field API formatter types.
  1003. *
  1004. * @param $info
  1005. * Array of informations on formatter types exposed by
  1006. * hook_field_field_formatter_info() implementations.
  1007. */
  1008. function hook_field_formatter_info_alter(&$info) {
  1009. // Add a setting to a formatter type.
  1010. $info['text_default']['settings'] += array(
  1011. 'mymodule_additional_setting' => 'default value',
  1012. );
  1013. // Let a new field type re-use an existing formatter.
  1014. $info['text_default']['field types'][] = 'my_field_type';
  1015. }
  1016. /**
  1017. * Allow formatters to load information for field values being displayed.
  1018. *
  1019. * This should be used when a formatter needs to load additional information
  1020. * from the database in order to render a field, for example a reference field
  1021. * which displays properties of the referenced entities such as name or type.
  1022. *
  1023. * This hook is called after the field type's own hook_field_prepare_view().
  1024. *
  1025. * Unlike most other field hooks, this hook operates on multiple entities. The
  1026. * $entities, $instances and $items parameters are arrays keyed by entity ID.
  1027. * For performance reasons, information for all available entities should be
  1028. * loaded in a single query where possible.
  1029. *
  1030. * @param $entity_type
  1031. * The type of $entity.
  1032. * @param $entities
  1033. * Array of entities being displayed, keyed by entity ID.
  1034. * @param $field
  1035. * The field structure for the operation.
  1036. * @param $instances
  1037. * Array of instance structures for $field for each entity, keyed by entity
  1038. * ID.
  1039. * @param $langcode
  1040. * The language the field values are to be shown in. If no language is
  1041. * provided the current language is used.
  1042. * @param $items
  1043. * Array of field values for the entities, keyed by entity ID.
  1044. * @param $displays
  1045. * Array of display settings to use for each entity, keyed by entity ID.
  1046. *
  1047. * @return
  1048. * Changes or additions to field values are done by altering the $items
  1049. * parameter by reference.
  1050. */
  1051. function hook_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  1052. $tids = array();
  1053. // Collect every possible term attached to any of the fieldable entities.
  1054. foreach ($entities as $id => $entity) {
  1055. foreach ($items[$id] as $delta => $item) {
  1056. // Force the array key to prevent duplicates.
  1057. $tids[$item['tid']] = $item['tid'];
  1058. }
  1059. }
  1060. if ($tids) {
  1061. $terms = taxonomy_term_load_multiple($tids);
  1062. // Iterate through the fieldable entities again to attach the loaded term
  1063. // data.
  1064. foreach ($entities as $id => $entity) {
  1065. $rekey = FALSE;
  1066. foreach ($items[$id] as $delta => $item) {
  1067. // Check whether the taxonomy term field instance value could be loaded.
  1068. if (isset($terms[$item['tid']])) {
  1069. // Replace the instance value with the term data.
  1070. $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
  1071. }
  1072. // Otherwise, unset the instance value, since the term does not exist.
  1073. else {
  1074. unset($items[$id][$delta]);
  1075. $rekey = TRUE;
  1076. }
  1077. }
  1078. if ($rekey) {
  1079. // Rekey the items array.
  1080. $items[$id] = array_values($items[$id]);
  1081. }
  1082. }
  1083. }
  1084. }
  1085. /**
  1086. * Build a renderable array for a field value.
  1087. *
  1088. * @param $entity_type
  1089. * The type of $entity.
  1090. * @param $entity
  1091. * The entity being displayed.
  1092. * @param $field
  1093. * The field structure.
  1094. * @param $instance
  1095. * The field instance.
  1096. * @param $langcode
  1097. * The language associated with $items.
  1098. * @param $items
  1099. * Array of values for this field.
  1100. * @param $display
  1101. * The display settings to use, as found in the 'display' entry of instance
  1102. * definitions. The array notably contains the following keys and values;
  1103. * - type: The name of the formatter to use.
  1104. * - settings: The array of formatter settings.
  1105. *
  1106. * @return
  1107. * A renderable array for the $items, as an array of child elements keyed
  1108. * by numeric indexes starting from 0.
  1109. */
  1110. function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  1111. $element = array();
  1112. $settings = $display['settings'];
  1113. switch ($display['type']) {
  1114. case 'sample_field_formatter_simple':
  1115. // Common case: each value is displayed individually in a sub-element
  1116. // keyed by delta. The field.tpl.php template specifies the markup
  1117. // wrapping each value.
  1118. foreach ($items as $delta => $item) {
  1119. $element[$delta] = array('#markup' => $settings['some_setting'] . $item['value']);
  1120. }
  1121. break;
  1122. case 'sample_field_formatter_themeable':
  1123. // More elaborate formatters can defer to a theme function for easier
  1124. // customization.
  1125. foreach ($items as $delta => $item) {
  1126. $element[$delta] = array(
  1127. '#theme' => 'mymodule_theme_sample_field_formatter_themeable',
  1128. '#data' => $item['value'],
  1129. '#some_setting' => $settings['some_setting'],
  1130. );
  1131. }
  1132. break;
  1133. case 'sample_field_formatter_combined':
  1134. // Some formatters might need to display all values within a single piece
  1135. // of markup.
  1136. $rows = array();
  1137. foreach ($items as $delta => $item) {
  1138. $rows[] = array($delta, $item['value']);
  1139. }
  1140. $element[0] = array(
  1141. '#theme' => 'table',
  1142. '#header' => array(t('Delta'), t('Value')),
  1143. '#rows' => $rows,
  1144. );
  1145. break;
  1146. }
  1147. return $element;
  1148. }
  1149. /**
  1150. * @} End of "defgroup field_formatter"
  1151. */
  1152. /**
  1153. * @ingroup field_attach
  1154. * @{
  1155. */
  1156. /**
  1157. * Act on field_attach_form().
  1158. *
  1159. * This hook is invoked after the field module has performed the operation.
  1160. * Implementing modules should alter the $form or $form_state parameters.
  1161. *
  1162. * @param $entity_type
  1163. * The type of $entity; for example, 'node' or 'user'.
  1164. * @param $entity
  1165. * The entity for which an edit form is being built.
  1166. * @param $form
  1167. * The form structure where field elements are attached to. This might be a
  1168. * full form structure, or a sub-element of a larger form. The
  1169. * $form['#parents'] property can be used to identify the corresponding part
  1170. * of $form_state['values']. Hook implementations that need to act on the
  1171. * top-level properties of the global form (like #submit, #validate...) can
  1172. * add a #process callback to the array received in the $form parameter, and
  1173. * act on the $complete_form parameter in the process callback.
  1174. * @param $form_state
  1175. * An associative array containing the current state of the form.
  1176. * @param $langcode
  1177. * The language the field values are going to be entered in. If no language
  1178. * is provided the default site language will be used.
  1179. */
  1180. function hook_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1181. // Add a checkbox allowing a given field to be emptied.
  1182. // See hook_field_attach_submit() for the corresponding processing code.
  1183. $form['empty_field_foo'] = array(
  1184. '#type' => 'checkbox',
  1185. '#title' => t("Empty the 'field_foo' field"),
  1186. );
  1187. }
  1188. /**
  1189. * Act on field_attach_load().
  1190. *
  1191. * This hook is invoked after the field module has performed the operation.
  1192. *
  1193. * Unlike other field_attach hooks, this hook accounts for 'multiple loads'.
  1194. * Instead of the usual $entity parameter, it accepts an array of entities,
  1195. * indexed by entity ID. For performance reasons, information for all available
  1196. * entities should be loaded in a single query where possible.
  1197. *
  1198. * The changes made to the entities' field values get cached by the field cache
  1199. * for subsequent loads.
  1200. *
  1201. * See field_attach_load() for details and arguments.
  1202. */
  1203. function hook_field_attach_load($entity_type, $entities, $age, $options) {
  1204. // @todo Needs function body.
  1205. }
  1206. /**
  1207. * Act on field_attach_validate().
  1208. *
  1209. * This hook is invoked after the field module has performed the operation.
  1210. *
  1211. * See field_attach_validate() for details and arguments.
  1212. */
  1213. function hook_field_attach_validate($entity_type, $entity, &$errors) {
  1214. // @todo Needs function body.
  1215. }
  1216. /**
  1217. * Act on field_attach_submit().
  1218. *
  1219. * This hook is invoked after the field module has performed the operation.
  1220. *
  1221. * @param $entity_type
  1222. * The type of $entity; for example, 'node' or 'user'.
  1223. * @param $entity
  1224. * The entity for which an edit form is being submitted. The incoming form
  1225. * values have been extracted as field values of the $entity object.
  1226. * @param $form
  1227. * The form structure where field elements are attached to. This might be a
  1228. * full form structure, or a sub-part of a larger form. The $form['#parents']
  1229. * property can be used to identify the corresponding part of
  1230. * $form_state['values'].
  1231. * @param $form_state
  1232. * An associative array containing the current state of the form.
  1233. */
  1234. function hook_field_attach_submit($entity_type, $entity, $form, &$form_state) {
  1235. // Sample case of an 'Empty the field' checkbox added on the form, allowing
  1236. // a given field to be emptied.
  1237. $values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
  1238. if (!empty($values['empty_field_foo'])) {
  1239. unset($entity->field_foo);
  1240. }
  1241. }
  1242. /**
  1243. * Act on field_attach_presave().
  1244. *
  1245. * This hook is invoked after the field module has performed the operation.
  1246. *
  1247. * See field_attach_presave() for details and arguments.
  1248. */
  1249. function hook_field_attach_presave($entity_type, $entity) {
  1250. // @todo Needs function body.
  1251. }
  1252. /**
  1253. * Act on field_attach_insert().
  1254. *
  1255. * This hook is invoked after the field module has performed the operation.
  1256. *
  1257. * See field_attach_insert() for details and arguments.
  1258. */
  1259. function hook_field_attach_insert($entity_type, $entity) {
  1260. // @todo Needs function body.
  1261. }
  1262. /**
  1263. * Act on field_attach_update().
  1264. *
  1265. * This hook is invoked after the field module has performed the operation.
  1266. *
  1267. * See field_attach_update() for details and arguments.
  1268. */
  1269. function hook_field_attach_update($entity_type, $entity) {
  1270. // @todo Needs function body.
  1271. }
  1272. /**
  1273. * Alter field_attach_preprocess() variables.
  1274. *
  1275. * This hook is invoked while preprocessing the field.tpl.php template file
  1276. * in field_attach_preprocess().
  1277. *
  1278. * @param $variables
  1279. * The variables array is passed by reference and will be populated with field
  1280. * values.
  1281. * @param $context
  1282. * An associative array containing:
  1283. * - entity_type: The type of $entity; for example, 'node' or 'user'.
  1284. * - entity: The entity with fields to render.
  1285. * - element: The structured array containing the values ready for rendering.
  1286. */
  1287. function hook_field_attach_preprocess_alter(&$variables, $context) {
  1288. // @todo Needs function body.
  1289. }
  1290. /**
  1291. * Act on field_attach_delete().
  1292. *
  1293. * This hook is invoked after the field module has performed the operation.
  1294. *
  1295. * See field_attach_delete() for details and arguments.
  1296. */
  1297. function hook_field_attach_delete($entity_type, $entity) {
  1298. // @todo Needs function body.
  1299. }
  1300. /**
  1301. * Act on field_attach_delete_revision().
  1302. *
  1303. * This hook is invoked after the field module has performed the operation.
  1304. *
  1305. * See field_attach_delete_revision() for details and arguments.
  1306. */
  1307. function hook_field_attach_delete_revision($entity_type, $entity) {
  1308. // @todo Needs function body.
  1309. }
  1310. /**
  1311. * Act on field_purge_data().
  1312. *
  1313. * This hook is invoked in field_purge_data() and allows modules to act on
  1314. * purging data from a single field pseudo-entity. For example, if a module
  1315. * relates data in the field with its own data, it may purge its own data
  1316. * during this process as well.
  1317. *
  1318. * @param $entity_type
  1319. * The type of $entity; for example, 'node' or 'user'.
  1320. * @param $entity
  1321. * The pseudo-entity whose field data is being purged.
  1322. * @param $field
  1323. * The (possibly deleted) field whose data is being purged.
  1324. * @param $instance
  1325. * The deleted field instance whose data is being purged.
  1326. *
  1327. * @see @link field_purge Field API bulk data deletion @endlink
  1328. * @see field_purge_data()
  1329. */
  1330. function hook_field_attach_purge($entity_type, $entity, $field, $instance) {
  1331. // find the corresponding data in mymodule and purge it
  1332. if ($entity_type == 'node' && $field->field_name == 'my_field_name') {
  1333. mymodule_remove_mydata($entity->nid);
  1334. }
  1335. }
  1336. /**
  1337. * Perform alterations on field_attach_view() or field_view_field().
  1338. *
  1339. * This hook is invoked after the field module has performed the operation.
  1340. *
  1341. * @param $output
  1342. * The structured content array tree for all of the entity's fields.
  1343. * @param $context
  1344. * An associative array containing:
  1345. * - entity_type: The type of $entity; for example, 'node' or 'user'.
  1346. * - entity: The entity with fields to render.
  1347. * - view_mode: View mode; for example, 'full' or 'teaser'.
  1348. * - display: Either a view mode string or an array of display settings. If
  1349. * this hook is being invoked from field_attach_view(), the 'display'
  1350. * element is set to the view mode string. If this hook is being invoked
  1351. * from field_view_field(), this element is set to the $display argument
  1352. * and the view_mode element is set to '_custom'. See field_view_field()
  1353. * for more information on what its $display argument contains.
  1354. * - language: The language code used for rendering.
  1355. */
  1356. function hook_field_attach_view_alter(&$output, $context) {
  1357. // Append RDF term mappings on displayed taxonomy links.
  1358. foreach (element_children($output) as $field_name) {
  1359. $element = &$output[$field_name];
  1360. if ($element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'taxonomy_term_reference_link') {
  1361. foreach ($element['#items'] as $delta => $item) {
  1362. $term = $item['taxonomy_term'];
  1363. if (!empty($term->rdf_mapping['rdftype'])) {
  1364. $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype'];
  1365. }
  1366. if (!empty($term->rdf_mapping['name']['predicates'])) {
  1367. $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates'];
  1368. }
  1369. }
  1370. }
  1371. }
  1372. }
  1373. /**
  1374. * Perform alterations on field_attach_prepare_translation().
  1375. *
  1376. * This hook is invoked after the field module has performed the operation.
  1377. *
  1378. * @param $entity
  1379. * The entity being prepared for translation.
  1380. * @param $context
  1381. * An associative array containing:
  1382. * - entity_type: The type of $entity; e.g. 'node' or 'user'.
  1383. * - langcode: The language the entity has to be translated in.
  1384. * - source_entity: The entity holding the field values to be translated.
  1385. * - source_langcode: The source language from which translate.
  1386. */
  1387. function hook_field_attach_prepare_translation_alter(&$entity, $context) {
  1388. if ($context['entity_type'] == 'custom_entity_type') {
  1389. $entity->custom_field = $context['source_entity']->custom_field;
  1390. }
  1391. }
  1392. /**
  1393. * Perform alterations on field_language() values.
  1394. *
  1395. * This hook is invoked to alter the array of display languages for the given
  1396. * entity.
  1397. *
  1398. * @param $display_language
  1399. * A reference to an array of language codes keyed by field name.
  1400. * @param $context
  1401. * An associative array containing:
  1402. * - entity_type: The type of the entity to be displayed.
  1403. * - entity: The entity with fields to render.
  1404. * - langcode: The language code $entity has to be displayed in.
  1405. */
  1406. function hook_field_language_alter(&$display_language, $context) {
  1407. // Do not apply core language fallback rules if they are disabled or if Locale
  1408. // is not registered as a translation handler.
  1409. if (variable_get('locale_field_language_fallback', TRUE) && field_has_translation_handler($context['entity_type'], 'locale')) {
  1410. locale_field_language_fallback($display_language, $context['entity'], $context['language']);
  1411. }
  1412. }
  1413. /**
  1414. * Alter field_available_languages() values.
  1415. *
  1416. * This hook is invoked from field_available_languages() to allow modules to
  1417. * alter the array of available languages for the given field.
  1418. *
  1419. * @param $languages
  1420. * A reference to an array of language codes to be made available.
  1421. * @param $context
  1422. * An associative array containing:
  1423. * - entity_type: The type of the entity the field is attached to.
  1424. * - field: A field data structure.
  1425. */
  1426. function hook_field_available_languages_alter(&$languages, $context) {
  1427. // Add an unavailable language.
  1428. $languages[] = 'xx';
  1429. // Remove an available language.
  1430. $index = array_search('yy', $languages);
  1431. unset($languages[$index]);
  1432. }
  1433. /**
  1434. * Act on field_attach_create_bundle().
  1435. *
  1436. * This hook is invoked after the field module has performed the operation.
  1437. *
  1438. * See field_attach_create_bundle() for details and arguments.
  1439. */
  1440. function hook_field_attach_create_bundle($entity_type, $bundle) {
  1441. // When a new bundle is created, the menu needs to be rebuilt to add the
  1442. // Field UI menu item tabs.
  1443. variable_set('menu_rebuild_needed', TRUE);
  1444. }
  1445. /**
  1446. * Act on field_attach_rename_bundle().
  1447. *
  1448. * This hook is invoked after the field module has performed the operation.
  1449. *
  1450. * See field_attach_rename_bundle() for details and arguments.
  1451. */
  1452. function hook_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  1453. // Update the extra weights variable with new information.
  1454. if ($bundle_old !== $bundle_new) {
  1455. $extra_weights = variable_get('field_extra_weights', array());
  1456. if (isset($info[$entity_type][$bundle_old])) {
  1457. $extra_weights[$entity_type][$bundle_new] = $extra_weights[$entity_type][$bundle_old];
  1458. unset($extra_weights[$entity_type][$bundle_old]);
  1459. variable_set('field_extra_weights', $extra_weights);
  1460. }
  1461. }
  1462. }
  1463. /**
  1464. * Act on field_attach_delete_bundle.
  1465. *
  1466. * This hook is invoked after the field module has performed the operation.
  1467. *
  1468. * @param $entity_type
  1469. * The type of entity; for example, 'node' or 'user'.
  1470. * @param $bundle
  1471. * The bundle that was just deleted.
  1472. * @param $instances
  1473. * An array of all instances that existed for the bundle before it was
  1474. * deleted.
  1475. */
  1476. function hook_field_attach_delete_bundle($entity_type, $bundle, $instances) {
  1477. // Remove the extra weights variable information for this bundle.
  1478. $extra_weights = variable_get('field_extra_weights', array());
  1479. if (isset($extra_weights[$entity_type][$bundle])) {
  1480. unset($extra_weights[$entity_type][$bundle]);
  1481. variable_set('field_extra_weights', $extra_weights);
  1482. }
  1483. }
  1484. /**
  1485. * @} End of "defgroup field_attach"
  1486. */
  1487. /**
  1488. * @ingroup field_storage
  1489. * @{
  1490. */
  1491. /**
  1492. * Expose Field API storage backends.
  1493. *
  1494. * @return
  1495. * An array describing the storage backends implemented by the module.
  1496. * The keys are storage backend names. To avoid name clashes, storage backend
  1497. * names should be prefixed with the name of the module that exposes them.
  1498. * The values are arrays describing the storage backend, with the following
  1499. * key/value pairs:
  1500. * - label: The human-readable name of the storage backend.
  1501. * - description: A short description for the storage backend.
  1502. * - settings: An array whose keys are the names of the settings available
  1503. * for the storage backend, and whose values are the default values for
  1504. * those settings.
  1505. */
  1506. function hook_field_storage_info() {
  1507. return array(
  1508. 'field_sql_storage' => array(
  1509. 'label' => t('Default SQL storage'),
  1510. 'description' => t('Stores fields in the local SQL database, using per-field tables.'),
  1511. 'settings' => array(),
  1512. ),
  1513. );
  1514. }
  1515. /**
  1516. * Perform alterations on Field API storage types.
  1517. *
  1518. * @param $info
  1519. * Array of informations on storage types exposed by
  1520. * hook_field_field_storage_info() implementations.
  1521. */
  1522. function hook_field_storage_info_alter(&$info) {
  1523. // Add a setting to a storage type.
  1524. $info['field_sql_storage']['settings'] += array(
  1525. 'mymodule_additional_setting' => 'default value',
  1526. );
  1527. }
  1528. /**
  1529. * Reveal the internal details about the storage for a field.
  1530. *
  1531. * For example, an SQL storage module might return the Schema API structure for
  1532. * the table. A key/value storage module might return the server name,
  1533. * authentication credentials, and bin name.
  1534. *
  1535. * Field storage modules are not obligated to implement this hook. Modules
  1536. * that rely on these details must only use them for read operations.
  1537. *
  1538. * @param $field
  1539. * A field structure.
  1540. *
  1541. * @return
  1542. * An array of details.
  1543. * - The first dimension is a store type (sql, solr, etc).
  1544. * - The second dimension indicates the age of the values in the store
  1545. * FIELD_LOAD_CURRENT or FIELD_LOAD_REVISION.
  1546. * - Other dimensions are specific to the field storage module.
  1547. *
  1548. * @see hook_field_storage_details_alter()
  1549. */
  1550. function hook_field_storage_details($field) {
  1551. $details = array();
  1552. // Add field columns.
  1553. foreach ((array) $field['columns'] as $column_name => $attributes) {
  1554. $real_name = _field_sql_storage_columnname($field['field_name'], $column_name);
  1555. $columns[$column_name] = $real_name;
  1556. }
  1557. return array(
  1558. 'sql' => array(
  1559. FIELD_LOAD_CURRENT => array(
  1560. _field_sql_storage_tablename($field) => $columns,
  1561. ),
  1562. FIELD_LOAD_REVISION => array(
  1563. _field_sql_storage_revision_tablename($field) => $columns,
  1564. ),
  1565. ),
  1566. );
  1567. }
  1568. /**
  1569. * Perform alterations on Field API storage details.
  1570. *
  1571. * @param $details
  1572. * An array of storage details for fields as exposed by
  1573. * hook_field_storage_details() implementations.
  1574. * @param $field
  1575. * A field structure.
  1576. *
  1577. * @see hook_field_storage_details()
  1578. */
  1579. function hook_field_storage_details_alter(&$details, $field) {
  1580. if ($field['field_name'] == 'field_of_interest') {
  1581. $columns = array();
  1582. foreach ((array) $field['columns'] as $column_name => $attributes) {
  1583. $columns[$column_name] = $column_name;
  1584. }
  1585. $details['drupal_variables'] = array(
  1586. FIELD_LOAD_CURRENT => array(
  1587. 'moon' => $columns,
  1588. ),
  1589. FIELD_LOAD_REVISION => array(
  1590. 'mars' => $columns,
  1591. ),
  1592. );
  1593. }
  1594. }
  1595. /**
  1596. * Load field data for a set of entities.
  1597. *
  1598. * This hook is invoked from field_attach_load() to ask the field storage
  1599. * module to load field data.
  1600. *
  1601. * Modules implementing this hook should load field values and add them to
  1602. * objects in $entities. Fields with no values should be added as empty
  1603. * arrays.
  1604. *
  1605. * @param $entity_type
  1606. * The type of entity, such as 'node' or 'user'.
  1607. * @param $entities
  1608. * The array of entity objects to add fields to, keyed by entity ID.
  1609. * @param $age
  1610. * FIELD_LOAD_CURRENT to load the most recent revision for all fields, or
  1611. * FIELD_LOAD_REVISION to load the version indicated by each entity.
  1612. * @param $fields
  1613. * An array listing the fields to be loaded. The keys of the array are field
  1614. * IDs, and the values of the array are the entity IDs (or revision IDs,
  1615. * depending on the $age parameter) to add each field to.
  1616. * @param $options
  1617. * An associative array of additional options, with the following keys:
  1618. * - deleted: If TRUE, deleted fields should be loaded as well as
  1619. * non-deleted fields. If unset or FALSE, only non-deleted fields should be
  1620. * loaded.
  1621. */
  1622. function hook_field_storage_load($entity_type, $entities, $age, $fields, $options) {
  1623. $field_info = field_info_field_by_ids();
  1624. $load_current = $age == FIELD_LOAD_CURRENT;
  1625. foreach ($fields as $field_id => $ids) {
  1626. $field = $field_info[$field_id];
  1627. $field_name = $field['field_name'];
  1628. $table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);
  1629. $query = db_select($table, 't')
  1630. ->fields('t')
  1631. ->condition('entity_type', $entity_type)
  1632. ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
  1633. ->condition('language', field_available_languages($entity_type, $field), 'IN')
  1634. ->orderBy('delta');
  1635. if (empty($options['deleted'])) {
  1636. $query->condition('deleted', 0);
  1637. }
  1638. $results = $query->execute();
  1639. $delta_count = array();
  1640. foreach ($results as $row) {
  1641. if (!isset($delta_count[$row->entity_id][$row->language])) {
  1642. $delta_count[$row->entity_id][$row->language] = 0;
  1643. }
  1644. if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta_count[$row->entity_id][$row->language] < $field['cardinality']) {
  1645. $item = array();
  1646. // For each column declared by the field, populate the item
  1647. // from the prefixed database column.
  1648. foreach ($field['columns'] as $column => $attributes) {
  1649. $column_name = _field_sql_storage_columnname($field_name, $column);
  1650. $item[$column] = $row->$column_name;
  1651. }
  1652. // Add the item to the field values for the entity.
  1653. $entities[$row->entity_id]->{$field_name}[$row->language][] = $item;
  1654. $delta_count[$row->entity_id][$row->language]++;
  1655. }
  1656. }
  1657. }
  1658. }
  1659. /**
  1660. * Write field data for an entity.
  1661. *
  1662. * This hook is invoked from field_attach_insert() and field_attach_update(),
  1663. * to ask the field storage module to save field data.
  1664. *
  1665. * @param $entity_type
  1666. * The entity type of entity, such as 'node' or 'user'.
  1667. * @param $entity
  1668. * The entity on which to operate.
  1669. * @param $op
  1670. * FIELD_STORAGE_UPDATE when updating an existing entity,
  1671. * FIELD_STORAGE_INSERT when inserting a new entity.
  1672. * @param $fields
  1673. * An array listing the fields to be written. The keys and values of the
  1674. * array are field IDs.
  1675. */
  1676. function hook_field_storage_write($entity_type, $entity, $op, $fields) {
  1677. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  1678. if (!isset($vid)) {
  1679. $vid = $id;
  1680. }
  1681. foreach ($fields as $field_id) {
  1682. $field = field_info_field_by_id($field_id);
  1683. $field_name = $field['field_name'];
  1684. $table_name = _field_sql_storage_tablename($field);
  1685. $revision_name = _field_sql_storage_revision_tablename($field);
  1686. $all_languages = field_available_languages($entity_type, $field);
  1687. $field_languages = array_intersect($all_languages, array_keys((array) $entity->$field_name));
  1688. // Delete and insert, rather than update, in case a value was added.
  1689. if ($op == FIELD_STORAGE_UPDATE) {
  1690. // Delete languages present in the incoming $entity->$field_name.
  1691. // Delete all languages if $entity->$field_name is empty.
  1692. $languages = !empty($entity->$field_name) ? $field_languages : $all_languages;
  1693. if ($languages) {
  1694. db_delete($table_name)
  1695. ->condition('entity_type', $entity_type)
  1696. ->condition('entity_id', $id)
  1697. ->condition('language', $languages, 'IN')
  1698. ->execute();
  1699. db_delete($revision_name)
  1700. ->condition('entity_type', $entity_type)
  1701. ->condition('entity_id', $id)
  1702. ->condition('revision_id', $vid)
  1703. ->condition('language', $languages, 'IN')
  1704. ->execute();
  1705. }
  1706. }
  1707. // Prepare the multi-insert query.
  1708. $do_insert = FALSE;
  1709. $columns = array('entity_type', 'entity_id', 'revision_id', 'bundle', 'delta', 'language');
  1710. foreach ($field['columns'] as $column => $attributes) {
  1711. $columns[] = _field_sql_storage_columnname($field_name, $column);
  1712. }
  1713. $query = db_insert($table_name)->fields($columns);
  1714. $revision_query = db_insert($revision_name)->fields($columns);
  1715. foreach ($field_languages as $langcode) {
  1716. $items = (array) $entity->{$field_name}[$langcode];
  1717. $delta_count = 0;
  1718. foreach ($items as $delta => $item) {
  1719. // We now know we have someting to insert.
  1720. $do_insert = TRUE;
  1721. $record = array(
  1722. 'entity_type' => $entity_type,
  1723. 'entity_id' => $id,
  1724. 'revision_id' => $vid,
  1725. 'bundle' => $bundle,
  1726. 'delta' => $delta,
  1727. 'language' => $langcode,
  1728. );
  1729. foreach ($field['columns'] as $column => $attributes) {
  1730. $record[_field_sql_storage_columnname($field_name, $column)] = isset($item[$column]) ? $item[$column] : NULL;
  1731. }
  1732. $query->values($record);
  1733. if (isset($vid)) {
  1734. $revision_query->values($record);
  1735. }
  1736. if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && ++$delta_count == $field['cardinality']) {
  1737. break;
  1738. }
  1739. }
  1740. }
  1741. // Execute the query if we have values to insert.
  1742. if ($do_insert) {
  1743. $query->execute();
  1744. $revision_query->execute();
  1745. }
  1746. }
  1747. }
  1748. /**
  1749. * Delete all field data for an entity.
  1750. *
  1751. * This hook is invoked from field_attach_delete() to ask the field storage
  1752. * module to delete field data.
  1753. *
  1754. * @param $entity_type
  1755. * The entity type of entity, such as 'node' or 'user'.
  1756. * @param $entity
  1757. * The entity on which to operate.
  1758. * @param $fields
  1759. * An array listing the fields to delete. The keys and values of the
  1760. * array are field IDs.
  1761. */
  1762. function hook_field_storage_delete($entity_type, $entity, $fields) {
  1763. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  1764. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  1765. if (isset($fields[$instance['field_id']])) {
  1766. $field = field_info_field_by_id($instance['field_id']);
  1767. field_sql_storage_field_storage_purge($entity_type, $entity, $field, $instance);
  1768. }
  1769. }
  1770. }
  1771. /**
  1772. * Delete a single revision of field data for an entity.
  1773. *
  1774. * This hook is invoked from field_attach_delete_revision() to ask the field
  1775. * storage module to delete field revision data.
  1776. *
  1777. * Deleting the current (most recently written) revision is not
  1778. * allowed as has undefined results.
  1779. *
  1780. * @param $entity_type
  1781. * The entity type of entity, such as 'node' or 'user'.
  1782. * @param $entity
  1783. * The entity on which to operate. The revision to delete is
  1784. * indicated by the entity's revision ID property, as identified by
  1785. * hook_fieldable_info() for $entity_type.
  1786. * @param $fields
  1787. * An array listing the fields to delete. The keys and values of the
  1788. * array are field IDs.
  1789. */
  1790. function hook_field_storage_delete_revision($entity_type, $entity, $fields) {
  1791. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  1792. if (isset($vid)) {
  1793. foreach ($fields as $field_id) {
  1794. $field = field_info_field_by_id($field_id);
  1795. $revision_name = _field_sql_storage_revision_tablename($field);
  1796. db_delete($revision_name)
  1797. ->condition('entity_type', $entity_type)
  1798. ->condition('entity_id', $id)
  1799. ->condition('revision_id', $vid)
  1800. ->execute();
  1801. }
  1802. }
  1803. }
  1804. /**
  1805. * Execute an EntityFieldQuery.
  1806. *
  1807. * This hook is called to find the entities having certain entity and field
  1808. * conditions and sort them in the given field order. If the field storage
  1809. * engine also handles property sorts and orders, it should unset those
  1810. * properties in the called object to signal that those have been handled.
  1811. *
  1812. * @param EntityFieldQuery $query
  1813. * An EntityFieldQuery.
  1814. *
  1815. * @return
  1816. * See EntityFieldQuery::execute() for the return values.
  1817. */
  1818. function hook_field_storage_query($query) {
  1819. $groups = array();
  1820. if ($query->age == FIELD_LOAD_CURRENT) {
  1821. $tablename_function = '_field_sql_storage_tablename';
  1822. $id_key = 'entity_id';
  1823. }
  1824. else {
  1825. $tablename_function = '_field_sql_storage_revision_tablename';
  1826. $id_key = 'revision_id';
  1827. }
  1828. $table_aliases = array();
  1829. // Add tables for the fields used.
  1830. foreach ($query->fields as $key => $field) {
  1831. $tablename = $tablename_function($field);
  1832. // Every field needs a new table.
  1833. $table_alias = $tablename . $key;
  1834. $table_aliases[$key] = $table_alias;
  1835. if ($key) {
  1836. $select_query->join($tablename, $table_alias, "$table_alias.entity_type = $field_base_table.entity_type AND $table_alias.$id_key = $field_base_table.$id_key");
  1837. }
  1838. else {
  1839. $select_query = db_select($tablename, $table_alias);
  1840. $select_query->addTag('entity_field_access');
  1841. $select_query->addMetaData('base_table', $tablename);
  1842. $select_query->fields($table_alias, array('entity_type', 'entity_id', 'revision_id', 'bundle'));
  1843. $field_base_table = $table_alias;
  1844. }
  1845. if ($field['cardinality'] != 1) {
  1846. $select_query->distinct();
  1847. }
  1848. }
  1849. // Add field conditions.
  1850. foreach ($query->fieldConditions as $key => $condition) {
  1851. $table_alias = $table_aliases[$key];
  1852. $field = $condition['field'];
  1853. // Add the specified condition.
  1854. $sql_field = "$table_alias." . _field_sql_storage_columnname($field['field_name'], $condition['column']);
  1855. $query->addCondition($select_query, $sql_field, $condition);
  1856. // Add delta / language group conditions.
  1857. foreach (array('delta', 'language') as $column) {
  1858. if (isset($condition[$column . '_group'])) {
  1859. $group_name = $condition[$column . '_group'];
  1860. if (!isset($groups[$column][$group_name])) {
  1861. $groups[$column][$group_name] = $table_alias;
  1862. }
  1863. else {
  1864. $select_query->where("$table_alias.$column = " . $groups[$column][$group_name] . ".$column");
  1865. }
  1866. }
  1867. }
  1868. }
  1869. if (isset($query->deleted)) {
  1870. $select_query->condition("$field_base_table.deleted", (int) $query->deleted);
  1871. }
  1872. // Is there a need to sort the query by property?
  1873. $has_property_order = FALSE;
  1874. foreach ($query->order as $order) {
  1875. if ($order['type'] == 'property') {
  1876. $has_property_order = TRUE;
  1877. }
  1878. }
  1879. if ($query->propertyConditions || $has_property_order) {
  1880. if (empty($query->entityConditions['entity_type']['value'])) {
  1881. throw new EntityFieldQueryException('Property conditions and orders must have an entity type defined.');
  1882. }
  1883. $entity_type = $query->entityConditions['entity_type']['value'];
  1884. $entity_base_table = _field_sql_storage_query_join_entity($select_query, $entity_type, $field_base_table);
  1885. $query->entityConditions['entity_type']['operator'] = '=';
  1886. foreach ($query->propertyConditions as $property_condition) {
  1887. $query->addCondition($select_query, "$entity_base_table." . $property_condition['column'], $property_condition);
  1888. }
  1889. }
  1890. foreach ($query->entityConditions as $key => $condition) {
  1891. $query->addCondition($select_query, "$field_base_table.$key", $condition);
  1892. }
  1893. // Order the query.
  1894. foreach ($query->order as $order) {
  1895. if ($order['type'] == 'entity') {
  1896. $key = $order['specifier'];
  1897. $select_query->orderBy("$field_base_table.$key", $order['direction']);
  1898. }
  1899. elseif ($order['type'] == 'field') {
  1900. $specifier = $order['specifier'];
  1901. $field = $specifier['field'];
  1902. $table_alias = $table_aliases[$specifier['index']];
  1903. $sql_field = "$table_alias." . _field_sql_storage_columnname($field['field_name'], $specifier['column']);
  1904. $select_query->orderBy($sql_field, $order['direction']);
  1905. }
  1906. elseif ($order['type'] == 'property') {
  1907. $select_query->orderBy("$entity_base_table." . $order['specifier'], $order['direction']);
  1908. }
  1909. }
  1910. return $query->finishQuery($select_query, $id_key);
  1911. }
  1912. /**
  1913. * Act on creation of a new field.
  1914. *
  1915. * This hook is invoked from field_create_field() to ask the field storage
  1916. * module to save field information and prepare for storing field instances.
  1917. * If there is a problem, the field storage module should throw an exception.
  1918. *
  1919. * @param $field
  1920. * The field structure being created.
  1921. */
  1922. function hook_field_storage_create_field($field) {
  1923. $schema = _field_sql_storage_schema($field);
  1924. foreach ($schema as $name => $table) {
  1925. db_create_table($name, $table);
  1926. }
  1927. drupal_get_schema(NULL, TRUE);
  1928. }
  1929. /**
  1930. * Act on deletion of a field.
  1931. *
  1932. * This hook is invoked from field_delete_field() to ask the field storage
  1933. * module to mark all information stored in the field for deletion.
  1934. *
  1935. * @param $field
  1936. * The field being deleted.
  1937. */
  1938. function hook_field_storage_delete_field($field) {
  1939. // Mark all data associated with the field for deletion.
  1940. $field['deleted'] = 0;
  1941. $table = _field_sql_storage_tablename($field);
  1942. $revision_table = _field_sql_storage_revision_tablename($field);
  1943. db_update($table)
  1944. ->fields(array('deleted' => 1))
  1945. ->execute();
  1946. // Move the table to a unique name while the table contents are being deleted.
  1947. $field['deleted'] = 1;
  1948. $new_table = _field_sql_storage_tablename($field);
  1949. $revision_new_table = _field_sql_storage_revision_tablename($field);
  1950. db_rename_table($table, $new_table);
  1951. db_rename_table($revision_table, $revision_new_table);
  1952. drupal_get_schema(NULL, TRUE);
  1953. }
  1954. /**
  1955. * Act on deletion of a field instance.
  1956. *
  1957. * This hook is invoked from field_delete_instance() to ask the field storage
  1958. * module to mark all information stored for the field instance for deletion.
  1959. *
  1960. * @param $instance
  1961. * The instance being deleted.
  1962. */
  1963. function hook_field_storage_delete_instance($instance) {
  1964. $field = field_info_field($instance['field_name']);
  1965. $table_name = _field_sql_storage_tablename($field);
  1966. $revision_name = _field_sql_storage_revision_tablename($field);
  1967. db_update($table_name)
  1968. ->fields(array('deleted' => 1))
  1969. ->condition('entity_type', $instance['entity_type'])
  1970. ->condition('bundle', $instance['bundle'])
  1971. ->execute();
  1972. db_update($revision_name)
  1973. ->fields(array('deleted' => 1))
  1974. ->condition('entity_type', $instance['entity_type'])
  1975. ->condition('bundle', $instance['bundle'])
  1976. ->execute();
  1977. }
  1978. /**
  1979. * Act before the storage backends load field data.
  1980. *
  1981. * This hook allows modules to load data before the Field Storage API,
  1982. * optionally preventing the field storage module from doing so.
  1983. *
  1984. * This lets 3rd party modules override, mirror, shard, or otherwise store a
  1985. * subset of fields in a different way than the current storage engine.
  1986. * Possible use cases include per-bundle storage, per-combo-field storage, etc.
  1987. *
  1988. * Modules implementing this hook should load field values and add them to
  1989. * objects in $entities. Fields with no values should be added as empty
  1990. * arrays. In addition, fields loaded should be added as keys to $skip_fields.
  1991. *
  1992. * @param $entity_type
  1993. * The type of entity, such as 'node' or 'user'.
  1994. * @param $entities
  1995. * The array of entity objects to add fields to, keyed by entity ID.
  1996. * @param $age
  1997. * FIELD_LOAD_CURRENT to load the most recent revision for all fields, or
  1998. * FIELD_LOAD_REVISION to load the version indicated by each entity.
  1999. * @param $skip_fields
  2000. * An array keyed by field IDs whose data has already been loaded and
  2001. * therefore should not be loaded again. Add a key to this array to indicate
  2002. * that your module has already loaded a field.
  2003. * @param $options
  2004. * An associative array of additional options, with the following keys:
  2005. * - field_id: The field ID that should be loaded. If unset, all fields
  2006. * should be loaded.
  2007. * - deleted: If TRUE, deleted fields should be loaded as well as
  2008. * non-deleted fields. If unset or FALSE, only non-deleted fields should be
  2009. * loaded.
  2010. */
  2011. function hook_field_storage_pre_load($entity_type, $entities, $age, &$skip_fields, $options) {
  2012. // @todo Needs function body.
  2013. }
  2014. /**
  2015. * Act before the storage backends insert field data.
  2016. *
  2017. * This hook allows modules to store data before the Field Storage API,
  2018. * optionally preventing the field storage module from doing so.
  2019. *
  2020. * @param $entity_type
  2021. * The type of $entity; for example, 'node' or 'user'.
  2022. * @param $entity
  2023. * The entity with fields to save.
  2024. * @param $skip_fields
  2025. * An array keyed by field IDs whose data has already been written and
  2026. * therefore should not be written again. The values associated with these
  2027. * keys are not specified.
  2028. * @return
  2029. * Saved field IDs are set set as keys in $skip_fields.
  2030. */
  2031. function hook_field_storage_pre_insert($entity_type, $entity, &$skip_fields) {
  2032. if ($entity_type == 'node' && $entity->status && _forum_node_check_node_type($entity)) {
  2033. $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
  2034. foreach ($entity->taxonomy_forums as $language) {
  2035. foreach ($language as $delta) {
  2036. $query->values(array(
  2037. 'nid' => $entity->nid,
  2038. 'title' => $entity->title,
  2039. 'tid' => $delta['value'],
  2040. 'sticky' => $entity->sticky,
  2041. 'created' => $entity->created,
  2042. 'comment_count' => 0,
  2043. 'last_comment_timestamp' => $entity->created,
  2044. ));
  2045. }
  2046. }
  2047. $query->execute();
  2048. }
  2049. }
  2050. /**
  2051. * Act before the storage backends update field data.
  2052. *
  2053. * This hook allows modules to store data before the Field Storage API,
  2054. * optionally preventing the field storage module from doing so.
  2055. *
  2056. * @param $entity_type
  2057. * The type of $entity; for example, 'node' or 'user'.
  2058. * @param $entity
  2059. * The entity with fields to save.
  2060. * @param $skip_fields
  2061. * An array keyed by field IDs whose data has already been written and
  2062. * therefore should not be written again. The values associated with these
  2063. * keys are not specified.
  2064. * @return
  2065. * Saved field IDs are set set as keys in $skip_fields.
  2066. */
  2067. function hook_field_storage_pre_update($entity_type, $entity, &$skip_fields) {
  2068. $first_call = &drupal_static(__FUNCTION__, array());
  2069. if ($entity_type == 'node' && $entity->status && _forum_node_check_node_type($entity)) {
  2070. // We don't maintain data for old revisions, so clear all previous values
  2071. // from the table. Since this hook runs once per field, per entity, make
  2072. // sure we only wipe values once.
  2073. if (!isset($first_call[$entity->nid])) {
  2074. $first_call[$entity->nid] = FALSE;
  2075. db_delete('forum_index')->condition('nid', $entity->nid)->execute();
  2076. }
  2077. // Only save data to the table if the node is published.
  2078. if ($entity->status) {
  2079. $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
  2080. foreach ($entity->taxonomy_forums as $language) {
  2081. foreach ($language as $delta) {
  2082. $query->values(array(
  2083. 'nid' => $entity->nid,
  2084. 'title' => $entity->title,
  2085. 'tid' => $delta['value'],
  2086. 'sticky' => $entity->sticky,
  2087. 'created' => $entity->created,
  2088. 'comment_count' => 0,
  2089. 'last_comment_timestamp' => $entity->created,
  2090. ));
  2091. }
  2092. }
  2093. $query->execute();
  2094. // The logic for determining last_comment_count is fairly complex, so
  2095. // call _forum_update_forum_index() too.
  2096. _forum_update_forum_index($entity->nid);
  2097. }
  2098. }
  2099. }
  2100. /**
  2101. * Returns the maximum weight for the entity components handled by the module.
  2102. *
  2103. * Field API takes care of fields and 'extra_fields'. This hook is intended for
  2104. * third-party modules adding other entity components (e.g. field_group).
  2105. *
  2106. * @param $entity_type
  2107. * The type of entity; e.g. 'node' or 'user'.
  2108. * @param $bundle
  2109. * The bundle name.
  2110. * @param $context
  2111. * The context for which the maximum weight is requested. Either 'form', or
  2112. * the name of a view mode.
  2113. * @return
  2114. * The maximum weight of the entity's components, or NULL if no components
  2115. * were found.
  2116. */
  2117. function hook_field_info_max_weight($entity_type, $bundle, $context) {
  2118. $weights = array();
  2119. foreach (my_module_entity_additions($entity_type, $bundle, $context) as $addition) {
  2120. $weights[] = $addition['weight'];
  2121. }
  2122. return $weights ? max($weights) : NULL;
  2123. }
  2124. /**
  2125. * Alters the display settings of a field before it gets displayed.
  2126. *
  2127. * Note that instead of hook_field_display_alter(), which is called for all
  2128. * fields on all entity types, hook_field_display_ENTITY_TYPE_alter() may be
  2129. * used to alter display settings for fields on a specific entity type only.
  2130. *
  2131. * This hook is called once per field per displayed entity. If the result of the
  2132. * hook involves reading from the database, it is highly recommended to
  2133. * statically cache the information.
  2134. *
  2135. * @param $display
  2136. * The display settings that will be used to display the field values, as
  2137. * found in the 'display' key of $instance definitions.
  2138. * @param $context
  2139. * An associative array containing:
  2140. * - entity_type: The entity type; e.g., 'node' or 'user'.
  2141. * - field: The field being rendered.
  2142. * - instance: The instance being rendered.
  2143. * - entity: The entity being rendered.
  2144. * - view_mode: The view mode, e.g. 'full', 'teaser'...
  2145. *
  2146. * @see hook_field_display_ENTITY_TYPE_alter()
  2147. */
  2148. function hook_field_display_alter(&$display, $context) {
  2149. // Leave field labels out of the search index.
  2150. // Note: The check against $context['entity_type'] == 'node' could be avoided
  2151. // by using hook_field_display_node_alter() instead of
  2152. // hook_field_display_alter(), resulting in less function calls when
  2153. // rendering non-node entities.
  2154. if ($context['entity_type'] == 'node' && $context['view_mode'] == 'search_index') {
  2155. $display['label'] = 'hidden';
  2156. }
  2157. }
  2158. /**
  2159. * Alters the display settings of a field on a given entity type before it gets displayed.
  2160. *
  2161. * Modules can implement hook_field_display_ENTITY_TYPE_alter() to alter display
  2162. * settings for fields on a specific entity type, rather than implementing
  2163. * hook_field_display_alter().
  2164. *
  2165. * This hook is called once per field per displayed entity. If the result of the
  2166. * hook involves reading from the database, it is highly recommended to
  2167. * statically cache the information.
  2168. *
  2169. * @param $display
  2170. * The display settings that will be used to display the field values, as
  2171. * found in the 'display' key of $instance definitions.
  2172. * @param $context
  2173. * An associative array containing:
  2174. * - entity_type: The entity type; e.g., 'node' or 'user'.
  2175. * - field: The field being rendered.
  2176. * - instance: The instance being rendered.
  2177. * - entity: The entity being rendered.
  2178. * - view_mode: The view mode, e.g. 'full', 'teaser'...
  2179. *
  2180. * @see hook_field_display_alter()
  2181. */
  2182. function hook_field_display_ENTITY_TYPE_alter(&$display, $context) {
  2183. // Leave field labels out of the search index.
  2184. if ($context['view_mode'] == 'search_index') {
  2185. $display['label'] = 'hidden';
  2186. }
  2187. }
  2188. /**
  2189. * Alters the display settings of pseudo-fields before an entity is displayed.
  2190. *
  2191. * This hook is called once per displayed entity. If the result of the hook
  2192. * involves reading from the database, it is highly recommended to statically
  2193. * cache the information.
  2194. *
  2195. * @param $displays
  2196. * An array of display settings for the pseudo-fields in the entity, keyed
  2197. * by pseudo-field names.
  2198. * @param $context
  2199. * An associative array containing:
  2200. * - entity_type: The entity type; e.g., 'node' or 'user'.
  2201. * - bundle: The bundle name.
  2202. * - view_mode: The view mode, e.g. 'full', 'teaser'...
  2203. */
  2204. function hook_field_extra_fields_display_alter(&$displays, $context) {
  2205. if ($context['entity_type'] == 'taxonomy_term' && $context['view_mode'] == 'full') {
  2206. $displays['description']['visible'] = FALSE;
  2207. }
  2208. }
  2209. /**
  2210. * Alters the widget properties of a field instance before it gets displayed.
  2211. *
  2212. * Note that instead of hook_field_widget_properties_alter(), which is called
  2213. * for all fields on all entity types,
  2214. * hook_field_widget_properties_ENTITY_TYPE_alter() may be used to alter widget
  2215. * properties for fields on a specific entity type only.
  2216. *
  2217. * This hook is called once per field per added or edit entity. If the result
  2218. * of the hook involves reading from the database, it is highly recommended to
  2219. * statically cache the information.
  2220. *
  2221. * @param $widget
  2222. * The instance's widget properties.
  2223. * @param $context
  2224. * An associative array containing:
  2225. * - entity_type: The entity type; e.g., 'node' or 'user'.
  2226. * - entity: The entity object.
  2227. * - field: The field that the widget belongs to.
  2228. * - instance: The instance of the field.
  2229. *
  2230. * @see hook_field_widget_properties_ENTITY_TYPE_alter()
  2231. */
  2232. function hook_field_widget_properties_alter(&$widget, $context) {
  2233. // Change a widget's type according to the time of day.
  2234. $field = $context['field'];
  2235. if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_foo') {
  2236. $time = date('H');
  2237. $widget['type'] = $time < 12 ? 'widget_am' : 'widget_pm';
  2238. }
  2239. }
  2240. /**
  2241. * Alters the widget properties of a field instance on a given entity type
  2242. * before it gets displayed.
  2243. *
  2244. * Modules can implement hook_field_widget_properties_ENTITY_TYPE_alter() to
  2245. * alter the widget properties for fields on a specific entity type, rather than
  2246. * implementing hook_field_widget_properties_alter().
  2247. *
  2248. * This hook is called once per field per displayed widget entity. If the result
  2249. * of the hook involves reading from the database, it is highly recommended to
  2250. * statically cache the information.
  2251. *
  2252. * @param $widget
  2253. * The instance's widget properties.
  2254. * @param $context
  2255. * An associative array containing:
  2256. * - entity_type: The entity type; e.g., 'node' or 'user'.
  2257. * - entity: The entity object.
  2258. * - field: The field that the widget belongs to.
  2259. * - instance: The instance of the field.
  2260. *
  2261. * @see hook_field_widget_properties_alter()
  2262. */
  2263. function hook_field_widget_properties_ENTITY_TYPE_alter(&$widget, $context) {
  2264. // Change a widget's type according to the time of day.
  2265. $field = $context['field'];
  2266. if ($field['field_name'] == 'field_foo') {
  2267. $time = date('H');
  2268. $widget['type'] = $time < 12 ? 'widget_am' : 'widget_pm';
  2269. }
  2270. }
  2271. /**
  2272. * @} End of "ingroup field_storage"
  2273. */
  2274. /**
  2275. * @ingroup field_crud
  2276. * @{
  2277. */
  2278. /**
  2279. * Act on a field being created.
  2280. *
  2281. * This hook is invoked from field_create_field() after the field is created, to
  2282. * allow modules to act on field creation.
  2283. *
  2284. * @param $field
  2285. * The field just created.
  2286. */
  2287. function hook_field_create_field($field) {
  2288. // @todo Needs function body.
  2289. }
  2290. /**
  2291. * Act on a field instance being created.
  2292. *
  2293. * This hook is invoked from field_create_instance() after the instance record
  2294. * is saved, so it cannot be used to modify the instance itself.
  2295. *
  2296. * @param $instance
  2297. * The instance just created.
  2298. */
  2299. function hook_field_create_instance($instance) {
  2300. // @todo Needs function body.
  2301. }
  2302. /**
  2303. * Forbid a field update from occurring.
  2304. *
  2305. * Any module may forbid any update for any reason. For example, the
  2306. * field's storage module might forbid an update if it would change
  2307. * the storage schema while data for the field exists. A field type
  2308. * module might forbid an update if it would change existing data's
  2309. * semantics, or if there are external dependencies on field settings
  2310. * that cannot be updated.
  2311. *
  2312. * To forbid the update from occurring, throw a FieldUpdateForbiddenException.
  2313. *
  2314. * @param $field
  2315. * The field as it will be post-update.
  2316. * @param $prior_field
  2317. * The field as it is pre-update.
  2318. * @param $has_data
  2319. * Whether any data already exists for this field.
  2320. */
  2321. function hook_field_update_forbid($field, $prior_field, $has_data) {
  2322. // A 'list' field stores integer keys mapped to display values. If
  2323. // the new field will have fewer values, and any data exists for the
  2324. // abandoned keys, the field will have no way to display them. So,
  2325. // forbid such an update.
  2326. if ($has_data && count($field['settings']['allowed_values']) < count($prior_field['settings']['allowed_values'])) {
  2327. // Identify the keys that will be lost.
  2328. $lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($prior_field['settings']['allowed_values']));
  2329. // If any data exist for those keys, forbid the update.
  2330. $query = new EntityFieldQuery();
  2331. $found = $query
  2332. ->fieldCondition($prior_field['field_name'], 'value', $lost_keys)
  2333. ->range(0, 1)
  2334. ->execute();
  2335. if ($found) {
  2336. throw new FieldUpdateForbiddenException("Cannot update a list field not to include keys with existing data");
  2337. }
  2338. }
  2339. }
  2340. /**
  2341. * Act on a field being updated.
  2342. *
  2343. * This hook is invoked just after field is updated in field_update_field().
  2344. *
  2345. * @param $field
  2346. * The field as it is post-update.
  2347. * @param $prior_field
  2348. * The field as it was pre-update.
  2349. * @param $has_data
  2350. * Whether any data already exists for this field.
  2351. */
  2352. function hook_field_update_field($field, $prior_field, $has_data) {
  2353. // Reset the static value that keeps track of allowed values for list fields.
  2354. drupal_static_reset('list_allowed_values');
  2355. }
  2356. /**
  2357. * Act on a field being deleted.
  2358. *
  2359. * This hook is invoked just after a field is deleted by field_delete_field().
  2360. *
  2361. * @param $field
  2362. * The field just deleted.
  2363. */
  2364. function hook_field_delete_field($field) {
  2365. // @todo Needs function body.
  2366. }
  2367. /**
  2368. * Act on a field instance being updated.
  2369. *
  2370. * This hook is invoked from field_update_instance() after the instance record
  2371. * is saved, so it cannot be used by a module to modify the instance itself.
  2372. *
  2373. * @param $instance
  2374. * The instance as it is post-update.
  2375. * @param $prior_$instance
  2376. * The instance as it was pre-update.
  2377. */
  2378. function hook_field_update_instance($instance, $prior_instance) {
  2379. // @todo Needs function body.
  2380. }
  2381. /**
  2382. * Act on a field instance being deleted.
  2383. *
  2384. * This hook is invoked from field_delete_instance() after the instance is
  2385. * deleted.
  2386. *
  2387. * @param $instance
  2388. * The instance just deleted.
  2389. */
  2390. function hook_field_delete_instance($instance) {
  2391. // @todo Needs function body.
  2392. }
  2393. /**
  2394. * Act on field records being read from the database.
  2395. *
  2396. * This hook is invoked from field_read_fields() on each field being read.
  2397. *
  2398. * @param $field
  2399. * The field record just read from the database.
  2400. */
  2401. function hook_field_read_field($field) {
  2402. // @todo Needs function body.
  2403. }
  2404. /**
  2405. * Act on a field record being read from the database.
  2406. *
  2407. * This hook is invoked from field_read_instances() on each instance being read.
  2408. *
  2409. * @param $instance
  2410. * The instance record just read from the database.
  2411. */
  2412. function hook_field_read_instance($instance) {
  2413. // @todo Needs function body.
  2414. }
  2415. /**
  2416. * Acts when a field record is being purged.
  2417. *
  2418. * In field_purge_field(), after the field configuration has been
  2419. * removed from the database, the field storage module has had a chance to
  2420. * run its hook_field_storage_purge_field(), and the field info cache
  2421. * has been cleared, this hook is invoked on all modules to allow them to
  2422. * respond to the field being purged.
  2423. *
  2424. * @param $field
  2425. * The field being purged.
  2426. */
  2427. function hook_field_purge_field($field) {
  2428. db_delete('my_module_field_info')
  2429. ->condition('id', $field['id'])
  2430. ->execute();
  2431. }
  2432. /**
  2433. * Acts when a field instance is being purged.
  2434. *
  2435. * In field_purge_instance(), after the field instance has been
  2436. * removed from the database, the field storage module has had a chance to
  2437. * run its hook_field_storage_purge_instance(), and the field info cache
  2438. * has been cleared, this hook is invoked on all modules to allow them to
  2439. * respond to the field instance being purged.
  2440. *
  2441. * @param $instance
  2442. * The instance being purged.
  2443. */
  2444. function hook_field_purge_instance($instance) {
  2445. db_delete('my_module_field_instance_info')
  2446. ->condition('id', $instance['id'])
  2447. ->execute();
  2448. }
  2449. /**
  2450. * Remove field storage information when a field record is purged.
  2451. *
  2452. * Called from field_purge_field() to allow the field storage module
  2453. * to remove field information when a field is being purged.
  2454. *
  2455. * @param $field
  2456. * The field being purged.
  2457. */
  2458. function hook_field_storage_purge_field($field) {
  2459. $table_name = _field_sql_storage_tablename($field);
  2460. $revision_name = _field_sql_storage_revision_tablename($field);
  2461. db_drop_table($table_name);
  2462. db_drop_table($revision_name);
  2463. }
  2464. /**
  2465. * Remove field storage information when a field instance is purged.
  2466. *
  2467. * Called from field_purge_instance() to allow the field storage module
  2468. * to remove field instance information when a field instance is being
  2469. * purged.
  2470. *
  2471. * @param $instance
  2472. * The instance being purged.
  2473. */
  2474. function hook_field_storage_purge_field_instance($instance) {
  2475. db_delete('my_module_field_instance_info')
  2476. ->condition('id', $instance['id'])
  2477. ->execute();
  2478. }
  2479. /**
  2480. * Remove field storage information when field data is purged.
  2481. *
  2482. * Called from field_purge_data() to allow the field storage
  2483. * module to delete field data information.
  2484. *
  2485. * @param $entity_type
  2486. * The type of $entity; for example, 'node' or 'user'.
  2487. * @param $entity
  2488. * The pseudo-entity whose field data to delete.
  2489. * @param $field
  2490. * The (possibly deleted) field whose data is being purged.
  2491. * @param $instance
  2492. * The deleted field instance whose data is being purged.
  2493. */
  2494. function hook_field_storage_purge($entity_type, $entity, $field, $instance) {
  2495. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  2496. $table_name = _field_sql_storage_tablename($field);
  2497. $revision_name = _field_sql_storage_revision_tablename($field);
  2498. db_delete($table_name)
  2499. ->condition('entity_type', $entity_type)
  2500. ->condition('entity_id', $id)
  2501. ->execute();
  2502. db_delete($revision_name)
  2503. ->condition('entity_type', $entity_type)
  2504. ->condition('entity_id', $id)
  2505. ->execute();
  2506. }
  2507. /**
  2508. * @} End of "ingroup field_crud"
  2509. */
  2510. /**
  2511. * Determine whether the user has access to a given field.
  2512. *
  2513. * This hook is invoked from field_access() to let modules block access to
  2514. * operations on fields. If no module returns FALSE, the operation is allowed.
  2515. *
  2516. * @param $op
  2517. * The operation to be performed. Possible values: 'edit', 'view'.
  2518. * @param $field
  2519. * The field on which the operation is to be performed.
  2520. * @param $entity_type
  2521. * The type of $entity; for example, 'node' or 'user'.
  2522. * @param $entity
  2523. * (optional) The entity for the operation.
  2524. * @param $account
  2525. * (optional) The account to check; if not given use currently logged in user.
  2526. *
  2527. * @return
  2528. * TRUE if the operation is allowed, and FALSE if the operation is denied.
  2529. */
  2530. function hook_field_access($op, $field, $entity_type, $entity, $account) {
  2531. if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
  2532. return user_access('edit field of interest', $account);
  2533. }
  2534. return TRUE;
  2535. }
  2536. /**
  2537. * @} End of "addtogroup hooks"
  2538. */
Login or register to post comments