field.attach.inc 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  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. * @param $entity_type
  913. * The type of $entity; e.g. 'node' or 'user'.
  914. * @param $entity
  915. * The entity with fields to save.
  916. */
  917. function field_attach_update($entity_type, $entity) {
  918. _field_invoke('update', $entity_type, $entity);
  919. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  920. // Let any module update field data before the storage engine, accumulating
  921. // saved fields along the way.
  922. $skip_fields = array();
  923. foreach (module_implements('field_storage_pre_update') as $module) {
  924. $function = $module . '_field_storage_pre_update';
  925. $function($entity_type, $entity, $skip_fields);
  926. }
  927. // Collect the storage backends used by the remaining fields in the entities.
  928. $storages = array();
  929. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  930. $field = field_info_field_by_id($instance['field_id']);
  931. $field_id = $field['id'];
  932. $field_name = $field['field_name'];
  933. // Leave the field untouched if $entity comes with no $field_name property,
  934. // but empty the field if it comes as a NULL value or an empty array.
  935. // Function property_exists() is slower, so we catch the more frequent
  936. // cases where it's an empty array with the faster isset().
  937. if (isset($entity->$field_name) || property_exists($entity, $field_name)) {
  938. // Collect the storage backend if the field has not been written yet.
  939. if (!isset($skip_fields[$field_id])) {
  940. $storages[$field['storage']['type']][$field_id] = $field_id;
  941. }
  942. }
  943. }
  944. // Field storage backends save any remaining unsaved fields.
  945. foreach ($storages as $storage => $fields) {
  946. $storage_info = field_info_storage_types($storage);
  947. module_invoke($storage_info['module'], 'field_storage_write', $entity_type, $entity, FIELD_STORAGE_UPDATE, $fields);
  948. }
  949. // Let other modules act on updating the entity.
  950. module_invoke_all('field_attach_update', $entity_type, $entity);
  951. $entity_info = entity_get_info($entity_type);
  952. if ($entity_info['field cache']) {
  953. cache_clear_all("field:$entity_type:$id", 'cache_field');
  954. }
  955. }
  956. /**
  957. * Delete field data for an existing entity. This deletes all
  958. * revisions of field data for the entity.
  959. *
  960. * @param $entity_type
  961. * The type of $entity; e.g. 'node' or 'user'.
  962. * @param $entity
  963. * The entity whose field data to delete.
  964. */
  965. function field_attach_delete($entity_type, $entity) {
  966. _field_invoke('delete', $entity_type, $entity);
  967. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  968. // Collect the storage backends used by the fields in the entities.
  969. $storages = array();
  970. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  971. $field = field_info_field_by_id($instance['field_id']);
  972. $field_id = $field['id'];
  973. $storages[$field['storage']['type']][$field_id] = $field_id;
  974. }
  975. // Field storage backends delete their data.
  976. foreach ($storages as $storage => $fields) {
  977. $storage_info = field_info_storage_types($storage);
  978. module_invoke($storage_info['module'], 'field_storage_delete', $entity_type, $entity, $fields);
  979. }
  980. // Let other modules act on deleting the entity.
  981. module_invoke_all('field_attach_delete', $entity_type, $entity);
  982. $entity_info = entity_get_info($entity_type);
  983. if ($entity_info['field cache']) {
  984. cache_clear_all("field:$entity_type:$id", 'cache_field');
  985. }
  986. }
  987. /**
  988. * Delete field data for a single revision of an existing entity. The
  989. * passed entity must have a revision id attribute.
  990. *
  991. * @param $entity_type
  992. * The type of $entity; e.g. 'node' or 'user'.
  993. * @param $entity
  994. * The entity with fields to save.
  995. */
  996. function field_attach_delete_revision($entity_type, $entity) {
  997. _field_invoke('delete_revision', $entity_type, $entity);
  998. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  999. // Collect the storage backends used by the fields in the entities.
  1000. $storages = array();
  1001. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  1002. $field = field_info_field_by_id($instance['field_id']);
  1003. $field_id = $field['id'];
  1004. $storages[$field['storage']['type']][$field_id] = $field_id;
  1005. }
  1006. // Field storage backends delete their data.
  1007. foreach ($storages as $storage => $fields) {
  1008. $storage_info = field_info_storage_types($storage);
  1009. module_invoke($storage_info['module'], 'field_storage_delete_revision', $entity_type, $entity, $fields);
  1010. }
  1011. // Let other modules act on deleting the revision.
  1012. module_invoke_all('field_attach_delete_revision', $entity_type, $entity);
  1013. }
  1014. /**
  1015. * Prepare field data prior to display.
  1016. *
  1017. * This function lets field types and formatters load additional data
  1018. * needed for display that is not automatically loaded during
  1019. * field_attach_load(). It accepts an array of entities to allow query
  1020. * optimisation when displaying lists of entities.
  1021. *
  1022. * field_attach_prepare_view() and field_attach_view() are two halves
  1023. * of the same operation. It is safe to call
  1024. * field_attach_prepare_view() multiple times on the same entity
  1025. * before calling field_attach_view() on it, but calling any Field
  1026. * API operation on an entity between passing that entity to these two
  1027. * functions may yield incorrect results.
  1028. *
  1029. * @param $entity_type
  1030. * The type of $entities; e.g. 'node' or 'user'.
  1031. * @param $entities
  1032. * An array of entities, keyed by entity id.
  1033. * @param $view_mode
  1034. * View mode, e.g. 'full', 'teaser'...
  1035. * @param $langcode
  1036. * (Optional) The language the field values are to be shown in. If no language
  1037. * is provided the current language is used.
  1038. * @param array $options
  1039. * An associative array of additional options. See _field_invoke() for
  1040. * details.
  1041. */
  1042. function field_attach_prepare_view($entity_type, $entities, $view_mode, $langcode = NULL, $options = array()) {
  1043. // Validate $options since this is a new parameter added after Drupal 7 was
  1044. // released.
  1045. $options = is_array($options) ? $options : array();
  1046. $options['language'] = array();
  1047. // To ensure hooks are only run once per entity, only process items without
  1048. // the _field_view_prepared flag.
  1049. // @todo: resolve this more generally for both entity and field level hooks.
  1050. $prepare = array();
  1051. foreach ($entities as $id => $entity) {
  1052. if (empty($entity->_field_view_prepared)) {
  1053. // Add this entity to the items to be prepared.
  1054. $prepare[$id] = $entity;
  1055. // Determine the actual language to display for each field, given the
  1056. // languages available in the field data.
  1057. $options['language'][$id] = field_language($entity_type, $entity, NULL, $langcode);
  1058. // Mark this item as prepared.
  1059. $entity->_field_view_prepared = TRUE;
  1060. }
  1061. }
  1062. $null = NULL;
  1063. // First let the field types do their preparation.
  1064. _field_invoke_multiple('prepare_view', $entity_type, $prepare, $null, $null, $options);
  1065. // Then let the formatters do their own specific massaging.
  1066. // field_default_prepare_view() takes care of dispatching to the correct
  1067. // formatters according to the display settings for the view mode.
  1068. _field_invoke_multiple_default('prepare_view', $entity_type, $prepare, $view_mode, $null, $options);
  1069. }
  1070. /**
  1071. * Returns a renderable array for the fields on an entity.
  1072. *
  1073. * Each field is displayed according to the display options specified in the
  1074. * $instance definition for the given $view_mode.
  1075. *
  1076. * field_attach_prepare_view() and field_attach_view() are two halves
  1077. * of the same operation. It is safe to call
  1078. * field_attach_prepare_view() multiple times on the same entity
  1079. * before calling field_attach_view() on it, but calling any Field
  1080. * API operation on an entity between passing that entity to these two
  1081. * functions may yield incorrect results.
  1082. *
  1083. * Sample structure:
  1084. * @code
  1085. * array(
  1086. * 'field_foo' => array(
  1087. * '#theme' => 'field',
  1088. * '#title' => the label of the field instance,
  1089. * '#label_display' => the label display mode,
  1090. * '#object' => the fieldable entity being displayed,
  1091. * '#entity_type' => the type of the entity being displayed,
  1092. * '#language' => the language of the field values being displayed,
  1093. * '#view_mode' => the view mode,
  1094. * '#field_name' => the name of the field,
  1095. * '#field_type' => the type of the field,
  1096. * '#formatter' => the name of the formatter,
  1097. * '#items' => the field values being displayed,
  1098. * // The element's children are the formatted values returned by
  1099. * // hook_field_formatter_view().
  1100. * ),
  1101. * );
  1102. * @endcode
  1103. *
  1104. * @param $entity_type
  1105. * The type of $entity; e.g. 'node' or 'user'.
  1106. * @param $entity
  1107. * The entity with fields to render.
  1108. * @param $view_mode
  1109. * View mode, e.g. 'full', 'teaser'...
  1110. * @param $langcode
  1111. * The language the field values are to be shown in. If no language is
  1112. * provided the current language is used.
  1113. * @param array $options
  1114. * An associative array of additional options. See _field_invoke() for
  1115. * details.
  1116. * @return
  1117. * A renderable array for the field values.
  1118. */
  1119. function field_attach_view($entity_type, $entity, $view_mode, $langcode = NULL, $options = array()) {
  1120. // Validate $options since this is a new parameter added after Drupal 7 was
  1121. // released.
  1122. $options = is_array($options) ? $options : array();
  1123. // Determine the actual language to display for each field, given the
  1124. // languages available in the field data.
  1125. $display_language = field_language($entity_type, $entity, NULL, $langcode);
  1126. $options['language'] = $display_language;
  1127. // Invoke field_default_view().
  1128. $null = NULL;
  1129. $output = _field_invoke_default('view', $entity_type, $entity, $view_mode, $null, $options);
  1130. // Add custom weight handling.
  1131. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  1132. $output['#pre_render'][] = '_field_extra_fields_pre_render';
  1133. $output['#entity_type'] = $entity_type;
  1134. $output['#bundle'] = $bundle;
  1135. // Let other modules alter the renderable array.
  1136. $context = array(
  1137. 'entity_type' => $entity_type,
  1138. 'entity' => $entity,
  1139. 'view_mode' => $view_mode,
  1140. 'display' => $view_mode,
  1141. 'language' => $langcode,
  1142. );
  1143. drupal_alter('field_attach_view', $output, $context);
  1144. // Reset the _field_view_prepared flag set in field_attach_prepare_view(),
  1145. // in case the same entity is displayed with different settings later in
  1146. // the request.
  1147. unset($entity->_field_view_prepared);
  1148. return $output;
  1149. }
  1150. /**
  1151. * Populate the template variables with the field values available for rendering.
  1152. *
  1153. * The $variables array will be populated with all the field instance values
  1154. * associated with the given entity type, keyed by field name; in case of
  1155. * translatable fields the language currently chosen for display will be
  1156. * selected.
  1157. *
  1158. * @param $entity_type
  1159. * The type of $entity; e.g. 'node' or 'user'.
  1160. * @param $entity
  1161. * The entity with fields to render.
  1162. * @param $element
  1163. * The structured array containing the values ready for rendering.
  1164. * @param $variables
  1165. * The variables array is passed by reference and will be populated with field
  1166. * values.
  1167. */
  1168. function field_attach_preprocess($entity_type, $entity, $element, &$variables) {
  1169. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  1170. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  1171. $field_name = $instance['field_name'];
  1172. if (isset($element[$field_name]['#language'])) {
  1173. $langcode = $element[$field_name]['#language'];
  1174. $variables[$field_name] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : NULL;
  1175. }
  1176. }
  1177. // Let other modules make changes to the $variables array.
  1178. $context = array(
  1179. 'entity_type' => $entity_type,
  1180. 'entity' => $entity,
  1181. 'element' => $element,
  1182. );
  1183. drupal_alter('field_attach_preprocess', $variables, $context);
  1184. }
  1185. /**
  1186. * Prepares an entity for translation.
  1187. *
  1188. * This function is used to fill-in the form default values for Field API fields
  1189. * while performing entity translation. By default it copies all the source
  1190. * values in the given source language to the new entity and assigns them the
  1191. * target language.
  1192. *
  1193. * This is used as part of the 'per entity' translation pattern, which is
  1194. * implemented only for nodes by translation.module. Other entity types may be
  1195. * supported through contributed modules.
  1196. *
  1197. * @param $entity_type
  1198. * The type of $entity; e.g. 'node' or 'user'.
  1199. * @param $entity
  1200. * The entity to be prepared for translation.
  1201. * @param $langcode
  1202. * The language the entity has to be translated in.
  1203. * @param $source_entity
  1204. * The source entity holding the field values to be translated.
  1205. * @param $source_langcode
  1206. * The source language from which translate.
  1207. */
  1208. function field_attach_prepare_translation($entity_type, $entity, $langcode, $source_entity, $source_langcode) {
  1209. $options = array('language' => $langcode);
  1210. // Copy source field values into the entity to be prepared.
  1211. _field_invoke_default('prepare_translation', $entity_type, $entity, $source_entity, $source_langcode, $options);
  1212. // Let field types handle their own advanced translation pattern if needed.
  1213. _field_invoke('prepare_translation', $entity_type, $entity, $source_entity, $source_langcode, $options);
  1214. // Let other modules alter the entity translation.
  1215. $context = array(
  1216. 'entity_type' => $entity_type,
  1217. 'langcode' => $langcode,
  1218. 'source_entity' => $source_entity,
  1219. 'source_langcode' => $source_langcode,
  1220. );
  1221. drupal_alter('field_attach_prepare_translation', $entity, $context);
  1222. }
  1223. /**
  1224. * Notify field.module that a new bundle was created.
  1225. *
  1226. * The default SQL-based storage doesn't need to do anything about it, but
  1227. * others might.
  1228. *
  1229. * @param $entity_type
  1230. * The entity type to which the bundle is bound.
  1231. * @param $bundle
  1232. * The name of the newly created bundle.
  1233. */
  1234. function field_attach_create_bundle($entity_type, $bundle) {
  1235. // Clear the cache.
  1236. field_cache_clear();
  1237. // Let other modules act on creating the bundle.
  1238. module_invoke_all('field_attach_create_bundle', $entity_type, $bundle);
  1239. }
  1240. /**
  1241. * Notify field.module that a bundle was renamed.
  1242. *
  1243. * @param $entity_type
  1244. * The entity type to which the bundle is bound.
  1245. * @param $bundle_old
  1246. * The previous name of the bundle.
  1247. * @param $bundle_new
  1248. * The new name of the bundle.
  1249. */
  1250. function field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  1251. db_update('field_config_instance')
  1252. ->fields(array('bundle' => $bundle_new))
  1253. ->condition('entity_type', $entity_type)
  1254. ->condition('bundle', $bundle_old)
  1255. ->execute();
  1256. // Clear the cache.
  1257. field_cache_clear();
  1258. // Update bundle settings.
  1259. $settings = variable_get('field_bundle_settings_' . $entity_type . '__' . $bundle_old, array());
  1260. variable_set('field_bundle_settings_' . $entity_type . '__' . $bundle_new, $settings);
  1261. variable_del('field_bundle_settings_' . $entity_type . '__' . $bundle_old);
  1262. // Let other modules act on renaming the bundle.
  1263. module_invoke_all('field_attach_rename_bundle', $entity_type, $bundle_old, $bundle_new);
  1264. }
  1265. /**
  1266. * Notify field.module the a bundle was deleted.
  1267. *
  1268. * This deletes the data for the field instances as well as the field instances
  1269. * themselves. This function actually just marks the data and field instances
  1270. * and deleted, leaving the garbage collection for a separate process, because
  1271. * it is not always possible to delete this much data in a single page request
  1272. * (particularly since for some field types, the deletion is more than just a
  1273. * simple DELETE query).
  1274. *
  1275. * @param $entity_type
  1276. * The entity type to which the bundle is bound.
  1277. * @param $bundle
  1278. * The bundle to delete.
  1279. */
  1280. function field_attach_delete_bundle($entity_type, $bundle) {
  1281. // First, delete the instances themselves. field_read_instances() must be
  1282. // used here since field_info_instances() does not return instances for
  1283. // disabled entity types or bundles.
  1284. $instances = field_read_instances(array('entity_type' => $entity_type, 'bundle' => $bundle), array('include_inactive' => 1));
  1285. foreach ($instances as $instance) {
  1286. field_delete_instance($instance);
  1287. }
  1288. // Clear the cache.
  1289. field_cache_clear();
  1290. // Clear bundle display settings.
  1291. variable_del('field_bundle_settings_' . $entity_type . '__' . $bundle);
  1292. // Let other modules act on deleting the bundle.
  1293. module_invoke_all('field_attach_delete_bundle', $entity_type, $bundle, $instances);
  1294. }
  1295. /**
  1296. * @} End of "defgroup field_attach".
  1297. */