field.attach.inc 55 KB

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