field.attach.inc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. <?php
  2. /**
  3. * @file
  4. * Field attach API, allowing entities (nodes, users, ...) to be 'fieldable'.
  5. */
  6. /**
  7. * Exception thrown by field_attach_validate() on field validation errors.
  8. */
  9. class FieldValidationException extends FieldException {
  10. var $errors;
  11. /**
  12. * Constructor for FieldValidationException.
  13. *
  14. * @param $errors
  15. * An array of field validation errors, keyed by field name and
  16. * delta that contains two keys:
  17. * - 'error': A machine-readable error code string, prefixed by
  18. * the field module name. A field widget may use this code to decide
  19. * how to report the error.
  20. * - 'message': A human-readable error message such as to be
  21. * passed to form_error() for the appropriate form element.
  22. */
  23. function __construct($errors) {
  24. $this->errors = $errors;
  25. parent::__construct(t('Field validation errors'));
  26. }
  27. }
  28. /**
  29. * @defgroup field_storage Field Storage API
  30. * @{
  31. * Implement a storage engine for Field API data.
  32. *
  33. * The Field Attach API uses the Field Storage API to perform all "database
  34. * access". Each Field Storage API hook function defines a primitive database
  35. * operation such as read, write, or delete. The default field storage module,
  36. * field_sql_storage.module, uses the local SQL database to implement these
  37. * operations, but alternative field storage backends can choose to represent
  38. * the data in SQL differently or use a completely different storage mechanism
  39. * such as a cloud-based database.
  40. *
  41. * Each field defines which storage backend it uses. The Drupal system variable
  42. * 'field_storage_default' identifies the storage backend used by default.
  43. *
  44. * See @link field Field API @endlink for information about the other parts of
  45. * the Field API.
  46. */
  47. /**
  48. * Argument for an update operation.
  49. *
  50. * This is used in hook_field_storage_write when updating an
  51. * existing entity.
  52. */
  53. define('FIELD_STORAGE_UPDATE', 'update');
  54. /**
  55. * Argument for an insert operation.
  56. *
  57. * This is used in hook_field_storage_write when inserting a new entity.
  58. */
  59. define('FIELD_STORAGE_INSERT', 'insert');
  60. /**
  61. * @} End of "defgroup field_storage".
  62. */
  63. /**
  64. * @defgroup field_attach Field Attach API
  65. * @{
  66. * Operate on Field API data attached to Drupal entities.
  67. *
  68. * Field Attach API functions load, store, display, generate Field API
  69. * structures, and perform a variety of other functions for field data attached
  70. * to individual entities.
  71. *
  72. * Field Attach API functions generally take $entity_type and $entity arguments
  73. * along with additional function-specific arguments. $entity_type is the type
  74. * of the fieldable entity, such as 'node' or 'user', and $entity is the entity
  75. * itself.
  76. *
  77. * hook_entity_info() is the central place for entity types to define if and
  78. * how Field API should operate on their entity objects. Notably, the
  79. * 'fieldable' property needs to be set to TRUE.
  80. *
  81. * The Field Attach API uses the concept of bundles: the set of fields for a
  82. * given entity is defined on a per-bundle basis. The collection of bundles for
  83. * an entity type is defined its hook_entity_info() implementation. For
  84. * instance, node_entity_info() exposes each node type as its own bundle. This
  85. * means that the set of fields of a node is determined by the node type. The
  86. * Field API reads the bundle name for a given entity from a particular
  87. * property of the entity object, and hook_entity_info() defines which property
  88. * to use. For instance, node_entity_info() specifies:
  89. * @code $info['entity keys']['bundle'] = 'type'@endcode
  90. * This indicates that for a particular node object, the bundle name can be
  91. * found in $node->type. This property can be omitted if the entity type only
  92. * exposes a single bundle (all entities of this type have the same collection
  93. * of fields). This is the case for the 'user' entity type.
  94. *
  95. * Most Field Attach API functions define a corresponding hook function that
  96. * allows any module to act on Field Attach operations for any entity after the
  97. * operation is complete, and access or modify all the field, form, or display
  98. * data for that entity and operation. For example, field_attach_view() invokes
  99. * hook_field_attach_view_alter(). These all-module hooks are distinct from
  100. * those of the Field Types API, such as hook_field_load(), that are only
  101. * invoked for the module that defines a specific field type.
  102. *
  103. * field_attach_load(), field_attach_insert(), and field_attach_update() also
  104. * define pre-operation hooks, e.g. hook_field_attach_pre_load(). These hooks
  105. * run before the corresponding Field Storage API and Field Type API
  106. * operations. They allow modules to define additional storage locations (e.g.
  107. * denormalizing, mirroring) for field data on a per-field basis. They also
  108. * allow modules to take over field storage completely by instructing other
  109. * implementations of the same hook and the Field Storage API itself not to
  110. * operate on specified fields.
  111. *
  112. * The pre-operation hooks do not make the Field Storage API irrelevant. The
  113. * Field Storage API is essentially the "fallback mechanism" for any fields
  114. * that aren't being intercepted explicitly by pre-operation hooks.
  115. *
  116. * @link field_language Field Language API @endlink provides information about
  117. * the structure of field objects.
  118. *
  119. * See @link field Field API @endlink for information about the other parts of
  120. * the Field API.
  121. */
  122. /**
  123. * Invoke a field hook.
  124. *
  125. * @param $op
  126. * Possible operations include:
  127. * - form
  128. * - validate
  129. * - presave
  130. * - insert
  131. * - update
  132. * - delete
  133. * - delete revision
  134. * - view
  135. * - prepare translation
  136. * @param $entity_type
  137. * The type of $entity; e.g. 'node' or 'user'.
  138. * @param $entity
  139. * The fully formed $entity_type entity.
  140. * @param $a
  141. * - The $form in the 'form' operation.
  142. * - The value of $view_mode in the 'view' operation.
  143. * - Otherwise NULL.
  144. * @param $b
  145. * - The $form_state in the 'submit' operation.
  146. * - Otherwise NULL.
  147. * @param $options
  148. * An associative array of additional options, with the following keys:
  149. * - 'field_name': The name of the field whose operation should be
  150. * invoked. By default, the operation is invoked on all the fields
  151. * in the entity's bundle. NOTE: This option is not compatible with
  152. * the 'deleted' option; the 'field_id' option should be used
  153. * instead.
  154. * - 'field_id': The id of the field whose operation should be
  155. * invoked. By default, the operation is invoked on all the fields
  156. * in the entity's' bundles.
  157. * - 'default': A boolean value, specifying which implementation of
  158. * the operation should be invoked.
  159. * - if FALSE (default), the field types implementation of the operation
  160. * will be invoked (hook_field_[op])
  161. * - If TRUE, the default field implementation of the field operation
  162. * will be invoked (field_default_[op])
  163. * Internal use only. Do not explicitely set to TRUE, but use
  164. * _field_invoke_default() instead.
  165. * - 'deleted': If TRUE, the function will operate on deleted fields
  166. * as well as non-deleted fields. If unset or FALSE, only
  167. * non-deleted fields are operated on.
  168. * - 'language': A language code or an array of language codes keyed by field
  169. * name. It will be used to narrow down to a single value the available
  170. * languages to act on.
  171. */
  172. function _field_invoke($op, $entity_type, $entity, &$a = NULL, &$b = NULL, $options = array()) {
  173. // Merge default options.
  174. $default_options = array(
  175. 'default' => FALSE,
  176. 'deleted' => FALSE,
  177. 'language' => NULL,
  178. );
  179. $options += $default_options;
  180. // Determine the list of instances to iterate on.
  181. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  182. $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  183. // Iterate through the instances and collect results.
  184. $return = array();
  185. foreach ($instances as $instance) {
  186. // field_info_field() is not available for deleted fields, so use
  187. // field_info_field_by_id().
  188. $field = field_info_field_by_id($instance['field_id']);
  189. $field_name = $field['field_name'];
  190. $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
  191. if (function_exists($function)) {
  192. // Determine the list of languages to iterate on.
  193. $available_languages = field_available_languages($entity_type, $field);
  194. $languages = _field_language_suggestion($available_languages, $options['language'], $field_name);
  195. foreach ($languages as $langcode) {
  196. $items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
  197. $result = $function($entity_type, $entity, $field, $instance, $langcode, $items, $a, $b);
  198. if (isset($result)) {
  199. // For hooks with array results, we merge results together.
  200. // For hooks with scalar results, we collect results in an array.
  201. if (is_array($result)) {
  202. $return = array_merge($return, $result);
  203. }
  204. else {
  205. $return[] = $result;
  206. }
  207. }
  208. // Populate $items back in the field values, but avoid replacing missing
  209. // fields with an empty array (those are not equivalent on update).
  210. if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
  211. $entity->{$field_name}[$langcode] = $items;
  212. }
  213. }
  214. }
  215. }
  216. return $return;
  217. }
  218. /**
  219. * Invoke a field hook across fields on multiple entities.
  220. *
  221. * @param $op
  222. * Possible operations include:
  223. * - load
  224. * - prepare_view
  225. * For all other operations, use _field_invoke() / field_invoke_default()
  226. * instead.
  227. * @param $entity_type
  228. * The type of $entity; e.g. 'node' or 'user'.
  229. * @param $entities
  230. * An array of entities, keyed by entity id.
  231. * @param $a
  232. * - The $age parameter in the 'load' operation.
  233. * - Otherwise NULL.
  234. * @param $b
  235. * Currently always NULL.
  236. * @param $options
  237. * An associative array of additional options, with the following keys:
  238. * - 'field_name': The name of the field whose operation should be
  239. * invoked. By default, the operation is invoked on all the fields
  240. * in the entity's bundle. NOTE: This option is not compatible with
  241. * the 'deleted' option; the 'field_id' option should be used instead.
  242. * - 'field_id': The id of the field whose operation should be
  243. * invoked. By default, the operation is invoked on all the fields
  244. * in the entity's' bundles.
  245. * - 'default': A boolean value, specifying which implementation of
  246. * the operation should be invoked.
  247. * - if FALSE (default), the field types implementation of the operation
  248. * will be invoked (hook_field_[op])
  249. * - If TRUE, the default field implementation of the field operation
  250. * will be invoked (field_default_[op])
  251. * Internal use only. Do not explicitely set to TRUE, but use
  252. * _field_invoke_multiple_default() instead.
  253. * - 'deleted': If TRUE, the function will operate on deleted fields
  254. * as well as non-deleted fields. If unset or FALSE, only
  255. * non-deleted fields are operated on.
  256. * - 'language': A language code or an array of arrays of language codes keyed
  257. * by entity id and field name. It will be used to narrow down to a single
  258. * value the available languages to act on.
  259. *
  260. * @return
  261. * An array of returned values keyed by entity id.
  262. */
  263. function _field_invoke_multiple($op, $entity_type, $entities, &$a = NULL, &$b = NULL, $options = array()) {
  264. // Merge default options.
  265. $default_options = array(
  266. 'default' => FALSE,
  267. 'deleted' => FALSE,
  268. 'language' => NULL,
  269. );
  270. $options += $default_options;
  271. $field_info = field_info_field_by_ids();
  272. $fields = array();
  273. $grouped_instances = array();
  274. $grouped_entities = array();
  275. $grouped_items = array();
  276. $return = array();
  277. // Go through the entities and collect the fields on which the hook should be
  278. // invoked.
  279. //
  280. // We group fields by id, not by name, because this function can operate on
  281. // deleted fields which may have non-unique names. However, entities can only
  282. // contain data for a single field for each name, even if that field
  283. // is deleted, so we reference field data via the
  284. // $entity->$field_name property.
  285. foreach ($entities as $entity) {
  286. // Determine the list of instances to iterate on.
  287. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  288. $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  289. foreach ($instances as $instance) {
  290. $field_id = $instance['field_id'];
  291. $field_name = $instance['field_name'];
  292. $field = $field_info[$field_id];
  293. $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
  294. if (function_exists($function)) {
  295. // Add the field to the list of fields to invoke the hook on.
  296. if (!isset($fields[$field_id])) {
  297. $fields[$field_id] = $field;
  298. }
  299. // Extract the field values into a separate variable, easily accessed
  300. // by hook implementations.
  301. // Unless a language suggestion is provided we iterate on all the
  302. // available languages.
  303. $available_languages = field_available_languages($entity_type, $field);
  304. $language = !empty($options['language'][$id]) ? $options['language'][$id] : $options['language'];
  305. $languages = _field_language_suggestion($available_languages, $language, $field_name);
  306. foreach ($languages as $langcode) {
  307. $grouped_items[$field_id][$langcode][$id] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
  308. // Group the instances and entities corresponding to the current
  309. // field.
  310. $grouped_instances[$field_id][$langcode][$id] = $instance;
  311. $grouped_entities[$field_id][$langcode][$id] = $entities[$id];
  312. }
  313. }
  314. }
  315. // Initialize the return value for each entity.
  316. $return[$id] = array();
  317. }
  318. // For each field, invoke the field hook and collect results.
  319. foreach ($fields as $field_id => $field) {
  320. $field_name = $field['field_name'];
  321. $function = $options['default'] ? 'field_default_' . $op : $field['module'] . '_field_' . $op;
  322. // Iterate over all the field translations.
  323. foreach ($grouped_items[$field_id] as $langcode => &$items) {
  324. $entities = $grouped_entities[$field_id][$langcode];
  325. $instances = $grouped_instances[$field_id][$langcode];
  326. $results = $function($entity_type, $entities, $field, $instances, $langcode, $items, $a, $b);
  327. if (isset($results)) {
  328. // Collect results by entity.
  329. // For hooks with array results, we merge results together.
  330. // For hooks with scalar results, we collect results in an array.
  331. foreach ($results as $id => $result) {
  332. if (is_array($result)) {
  333. $return[$id] = array_merge($return[$id], $result);
  334. }
  335. else {
  336. $return[$id][] = $result;
  337. }
  338. }
  339. }
  340. }
  341. // Populate field values back in the entities, but avoid replacing missing
  342. // fields with an empty array (those are not equivalent on update).
  343. foreach ($grouped_entities[$field_id] as $langcode => $entities) {
  344. foreach ($entities as $id => $entity) {
  345. if ($grouped_items[$field_id][$langcode][$id] !== array() || isset($entity->{$field_name}[$langcode])) {
  346. $entity->{$field_name}[$langcode] = $grouped_items[$field_id][$langcode][$id];
  347. }
  348. }
  349. }
  350. }
  351. return $return;
  352. }
  353. /**
  354. * Invoke field.module's version of a field hook.
  355. *
  356. * This function invokes the field_default_[op]() function.
  357. * Use _field_invoke() to invoke the field type implementation,
  358. * hook_field_[op]().
  359. *
  360. * @see _field_invoke()
  361. */
  362. function _field_invoke_default($op, $entity_type, $entity, &$a = NULL, &$b = NULL, $options = array()) {
  363. $options['default'] = TRUE;
  364. return _field_invoke($op, $entity_type, $entity, $a, $b, $options);
  365. }
  366. /**
  367. * Invoke field.module's version of a field hook on multiple entities.
  368. *
  369. * This function invokes the field_default_[op]() function.
  370. * Use _field_invoke_multiple() to invoke the field type implementation,
  371. * hook_field_[op]().
  372. *
  373. * @see _field_invoke_multiple()
  374. */
  375. function _field_invoke_multiple_default($op, $entity_type, $entities, &$a = NULL, &$b = NULL, $options = array()) {
  376. $options['default'] = TRUE;
  377. return _field_invoke_multiple($op, $entity_type, $entities, $a, $b, $options);
  378. }
  379. /**
  380. * Helper for _field_invoke(): retrieves a list of instances to operate on.
  381. *
  382. * @param $entity_type
  383. * The entity type.
  384. * @param $bundle
  385. * The bundle name.
  386. * @param $options
  387. * An associative array of options, as provided to _field_invoke(). Only the
  388. * following keys are considered :
  389. * - deleted
  390. * - field_name
  391. * - field_id
  392. * See _field_invoke() for details.
  393. *
  394. * @return
  395. * The array of selected instance definitions.
  396. */
  397. function _field_invoke_get_instances($entity_type, $bundle, $options) {
  398. if ($options['deleted']) {
  399. // Deleted fields are not included in field_info_instances(), and need to
  400. // be fetched from the database with field_read_instances().
  401. $params = array('entity_type' => $entity_type, 'bundle' => $bundle);
  402. if (isset($options['field_id'])) {
  403. // Single-field mode by field id: field_read_instances() does the filtering.
  404. // Single-field mode by field name is not compatible with the 'deleted'
  405. // option.
  406. $params['field_id'] = $options['field_id'];
  407. }
  408. $instances = field_read_instances($params, array('include_deleted' => TRUE));
  409. }
  410. elseif (isset($options['field_name'])) {
  411. // Single-field mode by field name: field_info_instance() does the
  412. // filtering.
  413. $instances = array(field_info_instance($entity_type, $options['field_name'], $bundle));
  414. }
  415. else {
  416. $instances = field_info_instances($entity_type, $bundle);
  417. if (isset($options['field_id'])) {
  418. // Single-field mode by field id: we need to loop on each instance to
  419. // find the right one.
  420. foreach ($instances as $instance) {
  421. if ($instance['field_id'] == $options['field_id']) {
  422. $instances = array($instance);
  423. break;
  424. }
  425. }
  426. }
  427. }
  428. return $instances;
  429. }
  430. /**
  431. * Add form elements for all fields for an entity to a form structure.
  432. *
  433. * The form elements for the entity's fields are added by reference as direct
  434. * children in the $form parameter. This parameter can be a full form structure
  435. * (most common case for entity edit forms), or a sub-element of a larger form.
  436. *
  437. * By default, submitted field values appear at the top-level of
  438. * $form_state['values']. A different location within $form_state['values'] can
  439. * be specified by setting the '#parents' property on the incoming $form
  440. * parameter. Because of name clashes, two instances of the same field cannot
  441. * appear within the same $form element, or within the same '#parents' space.
  442. *
  443. * For each call to field_attach_form(), field values are processed by calling
  444. * field_attach_form_validate() and field_attach_submit() on the same $form
  445. * element.
  446. *
  447. * Sample resulting structure in $form:
  448. * @code
  449. * '#parents' => The location of field values in $form_state['values'],
  450. * '#entity_type' => The name of the entity type,
  451. * '#bundle' => The name of the bundle,
  452. * // One sub-array per field appearing in the entity, keyed by field name.
  453. * // The structure of the array differs slightly depending on whether the
  454. * // widget is 'single-value' (provides the input for one field value,
  455. * // most common case), and will therefore be repeated as many times as
  456. * // needed, or 'multiple-values' (one single widget allows the input of
  457. * // several values, e.g checkboxes, select box...).
  458. * // The sub-array is nested into a $langcode key where $langcode has the
  459. * // same value of the $langcode parameter above.
  460. * // The '#language' key holds the same value of $langcode and it is used
  461. * // to access the field sub-array when $langcode is unknown.
  462. * 'field_foo' => array(
  463. * '#tree' => TRUE,
  464. * '#field_name' => The name of the field,
  465. * '#language' => $langcode,
  466. * $langcode => array(
  467. * '#field_name' => The name of the field,
  468. * '#language' => $langcode,
  469. * '#field_parents' => The 'parents' space for the field in the form,
  470. * equal to the #parents property of the $form parameter received by
  471. * field_attach_form(),
  472. * '#required' => Whether or not the field is required,
  473. * '#title' => The label of the field instance,
  474. * '#description' => The description text for the field instance,
  475. *
  476. * // Only for 'single' widgets:
  477. * '#theme' => 'field_multiple_value_form',
  478. * '#cardinality' => The field cardinality,
  479. * // One sub-array per copy of the widget, keyed by delta.
  480. * 0 => array(
  481. * '#entity_type' => The name of the entity type,
  482. * '#bundle' => The name of the bundle,
  483. * '#field_name' => The name of the field,
  484. * '#field_parents' => The 'parents' space for the field in the form,
  485. * equal to the #parents property of the $form parameter received by
  486. * field_attach_form(),
  487. * '#title' => The title to be displayed by the widget,
  488. * '#default_value' => The field value for delta 0,
  489. * '#required' => Whether the widget should be marked required,
  490. * '#delta' => 0,
  491. * '#columns' => The array of field columns,
  492. * // The remaining elements in the sub-array depend on the widget.
  493. * '#type' => The type of the widget,
  494. * ...
  495. * ),
  496. * 1 => array(
  497. * ...
  498. * ),
  499. *
  500. * // Only for multiple widgets:
  501. * '#entity_type' => The name of the entity type,
  502. * '#bundle' => $instance['bundle'],
  503. * '#columns' => array_keys($field['columns']),
  504. * // The remaining elements in the sub-array depend on the widget.
  505. * '#type' => The type of the widget,
  506. * ...
  507. * ),
  508. * ...
  509. * ),
  510. * )
  511. * @endcode
  512. *
  513. * Additionally, some processing data is placed in $form_state, and can be
  514. * accessed by field_form_get_state() and field_form_set_state().
  515. *
  516. * @param $entity_type
  517. * The type of $entity; e.g. 'node' or 'user'.
  518. * @param $entity
  519. * The entity for which to load form elements, used to initialize
  520. * default form values.
  521. * @param $form
  522. * The form structure to fill in. This can be a full form structure, or a
  523. * sub-element of a larger form. The #parents property can be set to control
  524. * the location of submitted field values within $form_state['values']. If
  525. * not specified, $form['#parents'] is set to an empty array, placing field
  526. * values at the top-level of $form_state['values'].
  527. * @param $form_state
  528. * An associative array containing the current state of the form.
  529. * @param $langcode
  530. * The language the field values are going to be entered, if no language
  531. * is provided the default site language will be used.
  532. *
  533. * @see field_form_get_state()
  534. * @see field_form_set_state()
  535. */
  536. function field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode = NULL) {
  537. // Set #parents to 'top-level' by default.
  538. $form += array('#parents' => array());
  539. // If no language is provided use the default site language.
  540. $options = array('language' => field_valid_language($langcode));
  541. $form += (array) _field_invoke_default('form', $entity_type, $entity, $form, $form_state, $options);
  542. // Add custom weight handling.
  543. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  544. $form['#pre_render'][] = '_field_extra_fields_pre_render';
  545. $form['#entity_type'] = $entity_type;
  546. $form['#bundle'] = $bundle;
  547. // Let other modules make changes to the form.
  548. // Avoid module_invoke_all() to let parameters be taken by reference.
  549. foreach (module_implements('field_attach_form') as $module) {
  550. $function = $module . '_field_attach_form';
  551. $function($entity_type, $entity, $form, $form_state, $langcode);
  552. }
  553. }
  554. /**
  555. * Loads fields for the current revisions of a group of entities.
  556. *
  557. * Loads all fields for each entity object in a group of a single entity type.
  558. * The loaded field values are added directly to the entity objects.
  559. *
  560. * field_attach_load() is automatically called by the default entity controller
  561. * class, and thus, in most cases, doesn't need to be explicitly called by the
  562. * entity type module.
  563. *
  564. * @param $entity_type
  565. * The type of $entity; e.g., 'node' or 'user'.
  566. * @param $entities
  567. * An array of entities for which to load fields, keyed by entity ID.
  568. * Each entity needs to have its 'bundle', 'id' and (if applicable)
  569. * 'revision' keys filled in. The function adds the loaded field data
  570. * directly in the entity objects of the $entities array.
  571. * @param $age
  572. * FIELD_LOAD_CURRENT to load the most recent revision for all
  573. * fields, or FIELD_LOAD_REVISION to load the version indicated by
  574. * each entity. Defaults to FIELD_LOAD_CURRENT; use
  575. * field_attach_load_revision() instead of passing FIELD_LOAD_REVISION.
  576. * @param $options
  577. * An associative array of additional options, with the following keys:
  578. * - 'field_id': The field ID that should be loaded, instead of
  579. * loading all fields, for each entity. Note that returned entities
  580. * may contain data for other fields, for example if they are read
  581. * from a cache.
  582. * - 'deleted': If TRUE, the function will operate on deleted fields
  583. * as well as non-deleted fields. If unset or FALSE, only
  584. * non-deleted fields are operated on.
  585. */
  586. function field_attach_load($entity_type, $entities, $age = FIELD_LOAD_CURRENT, $options = array()) {
  587. $field_info = field_info_field_by_ids();
  588. $load_current = $age == FIELD_LOAD_CURRENT;
  589. // Merge default options.
  590. $default_options = array(
  591. 'deleted' => FALSE,
  592. );
  593. $options += $default_options;
  594. $info = entity_get_info($entity_type);
  595. // Only the most current revision of non-deleted fields for cacheable entity
  596. // types can be cached.
  597. $cache_read = $load_current && $info['field cache'] && empty($options['deleted']);
  598. // In addition, do not write to the cache when loading a single field.
  599. $cache_write = $cache_read && !isset($options['field_id']);
  600. if (empty($entities)) {
  601. return;
  602. }
  603. // Assume all entities will need to be queried. Entities found in the cache
  604. // will be removed from the list.
  605. $queried_entities = $entities;
  606. // Fetch available entities from cache, if applicable.
  607. if ($cache_read) {
  608. // Build the list of cache entries to retrieve.
  609. $cids = array();
  610. foreach ($entities as $id => $entity) {
  611. $cids[] = "field:$entity_type:$id";
  612. }
  613. $cache = cache_get_multiple($cids, 'cache_field');
  614. // Put the cached field values back into the entities and remove them from
  615. // the list of entities to query.
  616. foreach ($entities as $id => $entity) {
  617. $cid = "field:$entity_type:$id";
  618. if (isset($cache[$cid])) {
  619. unset($queried_entities[$id]);
  620. foreach ($cache[$cid]->data as $field_name => $values) {
  621. $entity->$field_name = $values;
  622. }
  623. }
  624. }
  625. }
  626. // Fetch other entities from their storage location.
  627. if ($queried_entities) {
  628. // The invoke order is:
  629. // - hook_field_storage_pre_load()
  630. // - storage backend's hook_field_storage_load()
  631. // - field-type module's hook_field_load()
  632. // - hook_field_attach_load()
  633. // Invoke hook_field_storage_pre_load(): let any module load field
  634. // data before the storage engine, accumulating along the way.
  635. $skip_fields = array();
  636. foreach (module_implements('field_storage_pre_load') as $module) {
  637. $function = $module . '_field_storage_pre_load';
  638. $function($entity_type, $queried_entities, $age, $skip_fields, $options);
  639. }
  640. $instances = array();
  641. // Collect the storage backends used by the remaining fields in the entities.
  642. $storages = array();
  643. foreach ($queried_entities as $entity) {
  644. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  645. $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  646. foreach ($instances as $instance) {
  647. $field_name = $instance['field_name'];
  648. $field_id = $instance['field_id'];
  649. // Make sure all fields are present at least as empty arrays.
  650. if (!isset($queried_entities[$id]->{$field_name})) {
  651. $queried_entities[$id]->{$field_name} = array();
  652. }
  653. // Collect the storage backend if the field has not been loaded yet.
  654. if (!isset($skip_fields[$field_id])) {
  655. $field = $field_info[$field_id];
  656. $storages[$field['storage']['type']][$field_id][] = $load_current ? $id : $vid;
  657. }
  658. }
  659. }
  660. // Invoke hook_field_storage_load() on the relevant storage backends.
  661. foreach ($storages as $storage => $fields) {
  662. $storage_info = field_info_storage_types($storage);
  663. module_invoke($storage_info['module'], 'field_storage_load', $entity_type, $queried_entities, $age, $fields, $options);
  664. }
  665. // Invoke field-type module's hook_field_load().
  666. $null = NULL;
  667. _field_invoke_multiple('load', $entity_type, $queried_entities, $age, $null, $options);
  668. // Invoke hook_field_attach_load(): let other modules act on loading the
  669. // entitiy.
  670. module_invoke_all('field_attach_load', $entity_type, $queried_entities, $age, $options);
  671. // Build cache data.
  672. if ($cache_write) {
  673. foreach ($queried_entities as $id => $entity) {
  674. $data = array();
  675. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  676. $instances = field_info_instances($entity_type, $bundle);
  677. foreach ($instances as $instance) {
  678. $data[$instance['field_name']] = $queried_entities[$id]->{$instance['field_name']};
  679. }
  680. $cid = "field:$entity_type:$id";
  681. cache_set($cid, $data, 'cache_field');
  682. }
  683. }
  684. }
  685. }
  686. /**
  687. * Load all fields for previous versions of a group of entities.
  688. *
  689. * Loading different versions of the same entities is not supported, and should
  690. * be done by separate calls to the function.
  691. *
  692. * field_attach_load_revision() is automatically called by the default entity
  693. * controller class, and thus, in most cases, doesn't need to be explicitly
  694. * called by the entity type module.
  695. *
  696. * @param $entity_type
  697. * The type of $entity; e.g. 'node' or 'user'.
  698. * @param $entities
  699. * An array of entities for which to load fields, keyed by entity ID. Each
  700. * entity needs to have its 'bundle', 'id' and (if applicable) 'revision'
  701. * keys filled. The function adds the loaded field data directly in the
  702. * entity objects of the $entities array.
  703. * @param $options
  704. * An associative array of additional options. See field_attach_load() for
  705. * details.
  706. */
  707. function field_attach_load_revision($entity_type, $entities, $options = array()) {
  708. return field_attach_load($entity_type, $entities, FIELD_LOAD_REVISION, $options);
  709. }
  710. /**
  711. * Perform field validation against the field data in an entity.
  712. *
  713. * This function does not perform field widget validation on form
  714. * submissions. It is intended to be called during API save
  715. * operations. Use field_attach_form_validate() to validate form
  716. * submissions.
  717. *
  718. * @param $entity_type
  719. * The type of $entity; e.g. 'node' or 'user'.
  720. * @param $entity
  721. * The entity with fields to validate.
  722. * @throws FieldValidationException
  723. * If validation errors are found, a FieldValidationException is thrown. The
  724. * 'errors' property contains the array of errors, keyed by field name,
  725. * language and delta.
  726. */
  727. function field_attach_validate($entity_type, $entity) {
  728. $errors = array();
  729. // Check generic, field-type-agnostic errors first.
  730. _field_invoke_default('validate', $entity_type, $entity, $errors);
  731. // Check field-type specific errors.
  732. _field_invoke('validate', $entity_type, $entity, $errors);
  733. // Let other modules validate the entity.
  734. // Avoid module_invoke_all() to let $errors be taken by reference.
  735. foreach (module_implements('field_attach_validate') as $module) {
  736. $function = $module . '_field_attach_validate';
  737. $function($entity_type, $entity, $errors);
  738. }
  739. if ($errors) {
  740. throw new FieldValidationException($errors);
  741. }
  742. }
  743. /**
  744. * Perform field validation against form-submitted field values.
  745. *
  746. * There are two levels of validation for fields in forms: widget
  747. * validation, and field validation.
  748. * - Widget validation steps are specific to a given widget's own form
  749. * structure and UI metaphors. They are executed through FAPI's
  750. * #element_validate property during normal form validation.
  751. * - Field validation steps are common to a given field type, independently of
  752. * the specific widget being used in a given form. They are defined in the
  753. * field type's implementation of hook_field_validate().
  754. *
  755. * This function performs field validation in the context of a form
  756. * submission. It converts field validation errors into form errors
  757. * on the correct form elements. Fieldable entity types should call
  758. * this function during their own form validation function.
  759. *
  760. * @param $entity_type
  761. * The type of $entity; e.g. 'node' or 'user'.
  762. * @param $entity
  763. * The entity being submitted. The 'bundle', 'id' and (if applicable)
  764. * 'revision' keys should be present. The actual field values will be read
  765. * from $form_state['values'].
  766. * @param $form
  767. * The form structure where field elements are attached to. This might be a
  768. * full form structure, or a sub-element of a larger form.
  769. * @param $form_state
  770. * An associative array containing the current state of the form.
  771. */
  772. function field_attach_form_validate($entity_type, $entity, $form, &$form_state) {
  773. // Extract field values from submitted values.
  774. _field_invoke_default('extract_form_values', $entity_type, $entity, $form, $form_state);
  775. // Perform field_level validation.
  776. try {
  777. field_attach_validate($entity_type, $entity);
  778. }
  779. catch (FieldValidationException $e) {
  780. // Pass field-level validation errors back to widgets for accurate error
  781. // flagging.
  782. foreach ($e->errors as $field_name => $field_errors) {
  783. foreach ($field_errors as $langcode => $errors) {
  784. $field_state = field_form_get_state($form['#parents'], $field_name, $langcode, $form_state);
  785. $field_state['errors'] = $errors;
  786. field_form_set_state($form['#parents'], $field_name, $langcode, $form_state, $field_state);
  787. }
  788. }
  789. _field_invoke_default('form_errors', $entity_type, $entity, $form, $form_state);
  790. }
  791. }
  792. /**
  793. * Perform necessary operations on field data submitted by a form.
  794. *
  795. * Currently, this accounts for drag-and-drop reordering of
  796. * field values, and filtering of empty values.
  797. *
  798. * @param $entity_type
  799. * The type of $entity; e.g. 'node' or 'user'.
  800. * @param $entity
  801. * The entity being submitted. The 'bundle', 'id' and (if applicable)
  802. * 'revision' keys should be present. The actual field values will be read
  803. * from $form_state['values'].
  804. * @param $form
  805. * The form structure where field elements are attached to. This might be a
  806. * full form structure, or a sub-element of a larger form.
  807. * @param $form_state
  808. * An associative array containing the current state of the form.
  809. */
  810. function field_attach_submit($entity_type, $entity, $form, &$form_state) {
  811. // Extract field values from submitted values.
  812. _field_invoke_default('extract_form_values', $entity_type, $entity, $form, $form_state);
  813. _field_invoke_default('submit', $entity_type, $entity, $form, $form_state);
  814. // Let other modules act on submitting the entity.
  815. // Avoid module_invoke_all() to let $form_state be taken by reference.
  816. foreach (module_implements('field_attach_submit') as $module) {
  817. $function = $module . '_field_attach_submit';
  818. $function($entity_type, $entity, $form, $form_state);
  819. }
  820. }
  821. /**
  822. * Perform necessary operations just before fields data get saved.
  823. *
  824. * We take no specific action here, we just give other
  825. * modules the opportunity to act.
  826. *
  827. * @param $entity_type
  828. * The type of $entity; e.g. 'node' or 'user'.
  829. * @param $entity
  830. * The entity with fields to process.
  831. */
  832. function field_attach_presave($entity_type, $entity) {
  833. _field_invoke('presave', $entity_type, $entity);
  834. // Let other modules act on presaving the entity.
  835. module_invoke_all('field_attach_presave', $entity_type, $entity);
  836. }
  837. /**
  838. * Save field data for a new entity.
  839. *
  840. * The passed-in entity must already contain its id and (if applicable)
  841. * revision id attributes.
  842. * Default values (if any) will be saved for fields not present in the
  843. * $entity.
  844. *
  845. * @param $entity_type
  846. * The type of $entity; e.g. 'node' or 'user'.
  847. * @param $entity
  848. * The entity with fields to save.
  849. * @return
  850. * Default values (if any) will be added to the $entity parameter for fields
  851. * it leaves unspecified.
  852. */
  853. function field_attach_insert($entity_type, $entity) {
  854. _field_invoke_default('insert', $entity_type, $entity);
  855. _field_invoke('insert', $entity_type, $entity);
  856. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  857. // Let any module insert field data before the storage engine, accumulating
  858. // saved fields along the way.
  859. $skip_fields = array();
  860. foreach (module_implements('field_storage_pre_insert') as $module) {
  861. $function = $module . '_field_storage_pre_insert';
  862. $function($entity_type, $entity, $skip_fields);
  863. }
  864. // Collect the storage backends used by the remaining fields in the entities.
  865. $storages = array();
  866. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  867. $field = field_info_field_by_id($instance['field_id']);
  868. $field_id = $field['id'];
  869. $field_name = $field['field_name'];
  870. if (!empty($entity->$field_name)) {
  871. // Collect the storage backend if the field has not been written yet.
  872. if (!isset($skip_fields[$field_id])) {
  873. $storages[$field['storage']['type']][$field_id] = $field_id;
  874. }
  875. }
  876. }
  877. // Field storage backends save any remaining unsaved fields.
  878. foreach ($storages as $storage => $fields) {
  879. $storage_info = field_info_storage_types($storage);
  880. module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $entity, FIELD_STORAGE_INSERT, $fields);
  881. }
  882. // Let other modules act on inserting the entity.
  883. module_invoke_all('field_attach_insert', $entity_type, $entity);
  884. $entity_info = entity_get_info($entity_type);
  885. }
  886. /**
  887. * Save field data for an existing entity.
  888. *
  889. * @param $entity_type
  890. * The type of $entity; e.g. 'node' or 'user'.
  891. * @param $entity
  892. * The entity with fields to save.
  893. */
  894. function field_attach_update($entity_type, $entity) {
  895. _field_invoke('update', $entity_type, $entity);
  896. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  897. // Let any module update field data before the storage engine, accumulating
  898. // saved fields along the way.
  899. $skip_fields = array();
  900. foreach (module_implements('field_storage_pre_update') as $module) {
  901. $function = $module . '_field_storage_pre_update';
  902. $function($entity_type, $entity, $skip_fields);
  903. }
  904. // Collect the storage backends used by the remaining fields in the entities.
  905. $storages = array();
  906. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  907. $field = field_info_field_by_id($instance['field_id']);
  908. $field_id = $field['id'];
  909. $field_name = $field['field_name'];
  910. // Leave the field untouched if $entity comes with no $field_name property,
  911. // but empty the field if it comes as a NULL value or an empty array.
  912. // Function property_exists() is slower, so we catch the more frequent
  913. // cases where it's an empty array with the faster isset().
  914. if (isset($entity->$field_name) || property_exists($entity, $field_name)) {
  915. // Collect the storage backend if the field has not been written yet.
  916. if (!isset($skip_fields[$field_id])) {
  917. $storages[$field['storage']['type']][$field_id] = $field_id;
  918. }
  919. }
  920. }
  921. // Field storage backends save any remaining unsaved fields.
  922. foreach ($storages as $storage => $fields) {
  923. $storage_info = field_info_storage_types($storage);
  924. module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $entity, FIELD_STORAGE_UPDATE, $fields);
  925. }
  926. // Let other modules act on updating the entity.
  927. module_invoke_all('field_attach_update', $entity_type, $entity);
  928. $entity_info = entity_get_info($entity_type);
  929. if ($entity_info['field cache']) {
  930. cache_clear_all("field:$entity_type:$id", 'cache_field');
  931. }
  932. }
  933. /**
  934. * Delete field data for an existing entity. This deletes all
  935. * revisions of field data for the entity.
  936. *
  937. * @param $entity_type
  938. * The type of $entity; e.g. 'node' or 'user'.
  939. * @param $entity
  940. * The entity whose field data to delete.
  941. */
  942. function field_attach_delete($entity_type, $entity) {
  943. _field_invoke('delete', $entity_type, $entity);
  944. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  945. // Collect the storage backends used by the fields in the entities.
  946. $storages = array();
  947. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  948. $field = field_info_field_by_id($instance['field_id']);
  949. $field_id = $field['id'];
  950. $storages[$field['storage']['type']][$field_id] = $field_id;
  951. }
  952. // Field storage backends delete their data.
  953. foreach ($storages as $storage => $fields) {
  954. $storage_info = field_info_storage_types($storage);
  955. module_invoke($storage_info['module'], 'field_storage_delete', $entity_type, $entity, $fields);
  956. }
  957. // Let other modules act on deleting the entity.
  958. module_invoke_all('field_attach_delete', $entity_type, $entity);
  959. $entity_info = entity_get_info($entity_type);
  960. if ($entity_info['field cache']) {
  961. cache_clear_all("field:$entity_type:$id", 'cache_field');
  962. }
  963. }
  964. /**
  965. * Delete field data for a single revision of an existing entity. The
  966. * passed entity must have a revision id attribute.
  967. *
  968. * @param $entity_type
  969. * The type of $entity; e.g. 'node' or 'user'.
  970. * @param $entity
  971. * The entity with fields to save.
  972. */
  973. function field_attach_delete_revision($entity_type, $entity) {
  974. _field_invoke('delete_revision', $entity_type, $entity);
  975. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  976. // Collect the storage backends used by the fields in the entities.
  977. $storages = array();
  978. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  979. $field = field_info_field_by_id($instance['field_id']);
  980. $field_id = $field['id'];
  981. $storages[$field['storage']['type']][$field_id] = $field_id;
  982. }
  983. // Field storage backends delete their data.
  984. foreach ($storages as $storage => $fields) {
  985. $storage_info = field_info_storage_types($storage);
  986. module_invoke($storage_info['module'], 'field_storage_delete_revision', $entity_type, $entity, $fields);
  987. }
  988. // Let other modules act on deleting the revision.
  989. module_invoke_all('field_attach_delete_revision', $entity_type, $entity);
  990. }
  991. /**
  992. * Prepare field data prior to display.
  993. *
  994. * This function lets field types and formatters load additional data
  995. * needed for display that is not automatically loaded during
  996. * field_attach_load(). It accepts an array of entities to allow query
  997. * optimisation when displaying lists of entities.
  998. *
  999. * field_attach_prepare_view() and field_attach_view() are two halves
  1000. * of the same operation. It is safe to call
  1001. * field_attach_prepare_view() multiple times on the same entity
  1002. * before calling field_attach_view() on it, but calling any Field
  1003. * API operation on an entity between passing that entity to these two
  1004. * functions may yield incorrect results.
  1005. *
  1006. * @param $entity_type
  1007. * The type of $entities; e.g. 'node' or 'user'.
  1008. * @param $entities
  1009. * An array of entities, keyed by entity id.
  1010. * @param $view_mode
  1011. * View mode, e.g. 'full', 'teaser'...
  1012. * @param $langcode
  1013. * (Optional) The language the field values are to be shown in. If no language
  1014. * is provided the current language is used.
  1015. */
  1016. function field_attach_prepare_view($entity_type, $entities, $view_mode, $langcode = NULL) {
  1017. $options = array('language' => array());
  1018. // To ensure hooks are only run once per entity, only process items without
  1019. // the _field_view_prepared flag.
  1020. // @todo: resolve this more generally for both entity and field level hooks.
  1021. $prepare = array();
  1022. foreach ($entities as $id => $entity) {
  1023. if (empty($entity->_field_view_prepared)) {
  1024. // Add this entity to the items to be prepared.
  1025. $prepare[$id] = $entity;
  1026. // Determine the actual language to display for each field, given the
  1027. // languages available in the field data.
  1028. $options['language'][$id] = field_language($entity_type, $entity, NULL, $langcode);
  1029. // Mark this item as prepared.
  1030. $entity->_field_view_prepared = TRUE;
  1031. }
  1032. }
  1033. $null = NULL;
  1034. // First let the field types do their preparation.
  1035. _field_invoke_multiple('prepare_view', $entity_type, $prepare, $null, $null, $options);
  1036. // Then let the formatters do their own specific massaging.
  1037. // field_default_prepare_view() takes care of dispatching to the correct
  1038. // formatters according to the display settings for the view mode.
  1039. _field_invoke_multiple_default('prepare_view', $entity_type, $prepare, $view_mode, $null, $options);
  1040. }
  1041. /**
  1042. * Returns a renderable array for the fields on an entity.
  1043. *
  1044. * Each field is displayed according to the display options specified in the
  1045. * $instance definition for the given $view_mode.
  1046. *
  1047. * field_attach_prepare_view() and field_attach_view() are two halves
  1048. * of the same operation. It is safe to call
  1049. * field_attach_prepare_view() multiple times on the same entity
  1050. * before calling field_attach_view() on it, but calling any Field
  1051. * API operation on an entity between passing that entity to these two
  1052. * functions may yield incorrect results.
  1053. *
  1054. * Sample structure:
  1055. * @code
  1056. * array(
  1057. * 'field_foo' => array(
  1058. * '#theme' => 'field',
  1059. * '#title' => the label of the field instance,
  1060. * '#label_display' => the label display mode,
  1061. * '#object' => the fieldable entity being displayed,
  1062. * '#entity_type' => the type of the entity being displayed,
  1063. * '#language' => the language of the field values being displayed,
  1064. * '#view_mode' => the view mode,
  1065. * '#field_name' => the name of the field,
  1066. * '#field_type' => the type of the field,
  1067. * '#formatter' => the name of the formatter,
  1068. * '#items' => the field values being displayed,
  1069. * // The element's children are the formatted values returned by
  1070. * // hook_field_formatter_view().
  1071. * ),
  1072. * );
  1073. * @endcode
  1074. *
  1075. * @param $entity_type
  1076. * The type of $entity; e.g. 'node' or 'user'.
  1077. * @param $entity
  1078. * The entity with fields to render.
  1079. * @param $view_mode
  1080. * View mode, e.g. 'full', 'teaser'...
  1081. * @param $langcode
  1082. * The language the field values are to be shown in. If no language is
  1083. * provided the current language is used.
  1084. * @return
  1085. * A renderable array for the field values.
  1086. */
  1087. function field_attach_view($entity_type, $entity, $view_mode, $langcode = NULL) {
  1088. // Determine the actual language to display for each field, given the
  1089. // languages available in the field data.
  1090. $display_language = field_language($entity_type, $entity, NULL, $langcode);
  1091. $options = array('language' => $display_language);
  1092. // Invoke field_default_view().
  1093. $null = NULL;
  1094. $output = _field_invoke_default('view', $entity_type, $entity, $view_mode, $null, $options);
  1095. // Add custom weight handling.
  1096. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  1097. $output['#pre_render'][] = '_field_extra_fields_pre_render';
  1098. $output['#entity_type'] = $entity_type;
  1099. $output['#bundle'] = $bundle;
  1100. // Let other modules alter the renderable array.
  1101. $context = array(
  1102. 'entity_type' => $entity_type,
  1103. 'entity' => $entity,
  1104. 'view_mode' => $view_mode,
  1105. 'display' => $view_mode,
  1106. 'language' => $langcode,
  1107. );
  1108. drupal_alter('field_attach_view', $output, $context);
  1109. // Reset the _field_view_prepared flag set in field_attach_prepare_view(),
  1110. // in case the same entity is displayed with different settings later in
  1111. // the request.
  1112. unset($entity->_field_view_prepared);
  1113. return $output;
  1114. }
  1115. /**
  1116. * Populate the template variables with the field values available for rendering.
  1117. *
  1118. * The $variables array will be populated with all the field instance values
  1119. * associated with the given entity type, keyed by field name; in case of
  1120. * translatable fields the language currently chosen for display will be
  1121. * selected.
  1122. *
  1123. * @param $entity_type
  1124. * The type of $entity; e.g. 'node' or 'user'.
  1125. * @param $entity
  1126. * The entity with fields to render.
  1127. * @param $element
  1128. * The structured array containing the values ready for rendering.
  1129. * @param $variables
  1130. * The variables array is passed by reference and will be populated with field
  1131. * values.
  1132. */
  1133. function field_attach_preprocess($entity_type, $entity, $element, &$variables) {
  1134. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  1135. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  1136. $field_name = $instance['field_name'];
  1137. if (isset($element[$field_name]['#language'])) {
  1138. $langcode = $element[$field_name]['#language'];
  1139. $variables[$field_name] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : NULL;
  1140. }
  1141. }
  1142. // Let other modules make changes to the $variables array.
  1143. $context = array(
  1144. 'entity_type' => $entity_type,
  1145. 'entity' => $entity,
  1146. 'element' => $element,
  1147. );
  1148. drupal_alter('field_attach_preprocess', $variables, $context);
  1149. }
  1150. /**
  1151. * Prepares an entity for translation.
  1152. *
  1153. * This function is used to fill-in the form default values for Field API fields
  1154. * while performing entity translation. By default it copies all the source
  1155. * values in the given source language to the new entity and assigns them the
  1156. * target language.
  1157. *
  1158. * This is used as part of the 'per entity' translation pattern, which is
  1159. * implemented only for nodes by translation.module. Other entity types may be
  1160. * supported through contributed modules.
  1161. *
  1162. * @param $entity_type
  1163. * The type of $entity; e.g. 'node' or 'user'.
  1164. * @param $entity
  1165. * The entity to be prepared for translation.
  1166. * @param $langcode
  1167. * The language the entity has to be translated in.
  1168. * @param $source_entity
  1169. * The source entity holding the field values to be translated.
  1170. * @param $source_langcode
  1171. * The source language from which translate.
  1172. */
  1173. function field_attach_prepare_translation($entity_type, $entity, $langcode, $source_entity, $source_langcode) {
  1174. $options = array('language' => $langcode);
  1175. // Copy source field values into the entity to be prepared.
  1176. _field_invoke_default('prepare_translation', $entity_type, $entity, $source_entity, $source_langcode, $options);
  1177. // Let field types handle their own advanced translation pattern if needed.
  1178. _field_invoke('prepare_translation', $entity_type, $entity, $source_entity, $source_langcode, $options);
  1179. // Let other modules alter the entity translation.
  1180. $context = array(
  1181. 'entity_type' => $entity_type,
  1182. 'langcode' => $langcode,
  1183. 'source_entity' => $source_entity,
  1184. 'source_langcode' => $source_langcode,
  1185. );
  1186. drupal_alter('field_attach_prepare_translation', $entity, $context);
  1187. }
  1188. /**
  1189. * Notify field.module that a new bundle was created.
  1190. *
  1191. * The default SQL-based storage doesn't need to do anything about it, but
  1192. * others might.
  1193. *
  1194. * @param $entity_type
  1195. * The entity type to which the bundle is bound.
  1196. * @param $bundle
  1197. * The name of the newly created bundle.
  1198. */
  1199. function field_attach_create_bundle($entity_type, $bundle) {
  1200. // Clear the cache.
  1201. field_cache_clear();
  1202. // Let other modules act on creating the bundle.
  1203. module_invoke_all('field_attach_create_bundle', $entity_type, $bundle);
  1204. }
  1205. /**
  1206. * Notify field.module that a bundle was renamed.
  1207. *
  1208. * @param $entity_type
  1209. * The entity type to which the bundle is bound.
  1210. * @param $bundle_old
  1211. * The previous name of the bundle.
  1212. * @param $bundle_new
  1213. * The new name of the bundle.
  1214. */
  1215. function field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  1216. db_update('field_config_instance')
  1217. ->fields(array('bundle' => $bundle_new))
  1218. ->condition('entity_type', $entity_type)
  1219. ->condition('bundle', $bundle_old)
  1220. ->execute();
  1221. // Clear the cache.
  1222. field_cache_clear();
  1223. // Update bundle settings.
  1224. $settings = variable_get('field_bundle_settings_' . $entity_type . '__' . $bundle_old, array());
  1225. variable_set('field_bundle_settings_' . $entity_type . '__' . $bundle_new, $settings);
  1226. variable_del('field_bundle_settings_' . $entity_type . '__' . $bundle_old);
  1227. // Let other modules act on renaming the bundle.
  1228. module_invoke_all('field_attach_rename_bundle', $entity_type, $bundle_old, $bundle_new);
  1229. }
  1230. /**
  1231. * Notify field.module the a bundle was deleted.
  1232. *
  1233. * This deletes the data for the field instances as well as the field instances
  1234. * themselves. This function actually just marks the data and field instances
  1235. * and deleted, leaving the garbage collection for a separate process, because
  1236. * it is not always possible to delete this much data in a single page request
  1237. * (particularly since for some field types, the deletion is more than just a
  1238. * simple DELETE query).
  1239. *
  1240. * @param $entity_type
  1241. * The entity type to which the bundle is bound.
  1242. * @param $bundle
  1243. * The bundle to delete.
  1244. */
  1245. function field_attach_delete_bundle($entity_type, $bundle) {
  1246. // First, delete the instances themselves. field_read_instances() must be
  1247. // used here since field_info_instances() does not return instances for
  1248. // disabled entity types or bundles.
  1249. $instances = field_read_instances(array('entity_type' => $entity_type, 'bundle' => $bundle), array('include_inactive' => 1));
  1250. foreach ($instances as $instance) {
  1251. field_delete_instance($instance);
  1252. }
  1253. // Clear the cache.
  1254. field_cache_clear();
  1255. // Clear bundle display settings.
  1256. variable_del('field_bundle_settings_' . $entity_type . '__' . $bundle);
  1257. // Let other modules act on deleting the bundle.
  1258. module_invoke_all('field_attach_delete_bundle', $entity_type, $bundle, $instances);
  1259. }
  1260. /**
  1261. * @} End of "defgroup field_attach".
  1262. */