field.form.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. /**
  3. * @file
  4. * Field forms management.
  5. */
  6. /**
  7. * Creates a form element for a field and can populate it with a default value.
  8. *
  9. * If the form element is not associated with an entity (i.e., $entity is NULL)
  10. * field_get_default_value will be called to supply the default value for the
  11. * field. Also allows other modules to alter the form element by implementing
  12. * their own hooks.
  13. *
  14. * @param $entity_type
  15. * The type of entity (for example 'node' or 'user') that the field belongs
  16. * to.
  17. * @param $entity
  18. * The entity object that the field belongs to. This may be NULL if creating a
  19. * form element with a default value.
  20. * @param $field
  21. * An array representing the field whose editing element is being created.
  22. * @param $instance
  23. * An array representing the structure for $field in its current context.
  24. * @param $langcode
  25. * The language associated with the field.
  26. * @param $items
  27. * An array of the field values. When creating a new entity this may be NULL
  28. * or an empty array to use default values.
  29. * @param $form
  30. * An array representing the form that the editing element will be attached
  31. * to.
  32. * @param $form_state
  33. * An array containing the current state of the form.
  34. * @param $get_delta
  35. * Used to get only a specific delta value of a multiple value field.
  36. *
  37. * @return
  38. * The form element array created for this field.
  39. */
  40. function field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, &$form, &$form_state, $get_delta = NULL) {
  41. // This could be called with no entity, as when a UI module creates a
  42. // dummy form to set default values.
  43. if ($entity) {
  44. list($id, , ) = entity_extract_ids($entity_type, $entity);
  45. }
  46. $parents = $form['#parents'];
  47. $addition = array();
  48. $field_name = $field['field_name'];
  49. $addition[$field_name] = array();
  50. // Populate widgets with default values when creating a new entity.
  51. if (empty($items) && empty($id)) {
  52. $items = field_get_default_value($entity_type, $entity, $field, $instance, $langcode);
  53. }
  54. // Let modules alter the widget properties.
  55. $context = array(
  56. 'entity_type' => $entity_type,
  57. 'entity' => $entity,
  58. 'field' => $field,
  59. 'instance' => $instance,
  60. );
  61. drupal_alter(array('field_widget_properties', 'field_widget_properties_' . $entity_type), $instance['widget'], $context);
  62. // Collect widget elements.
  63. $elements = array();
  64. // Store field information in $form_state.
  65. if (!field_form_get_state($parents, $field_name, $langcode, $form_state)) {
  66. $field_state = array(
  67. 'field' => $field,
  68. 'instance' => $instance,
  69. 'items_count' => count($items),
  70. 'array_parents' => array(),
  71. 'errors' => array(),
  72. );
  73. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  74. }
  75. // If field module handles multiple values for this form element, and we are
  76. // not displaying an individual element, process the multiple value form.
  77. if (!isset($get_delta) && field_behaviors_widget('multiple values', $instance) == FIELD_BEHAVIOR_DEFAULT) {
  78. // Store the entity in the form.
  79. $form['#entity'] = $entity;
  80. $elements = field_multiple_value_form($field, $instance, $langcode, $items, $form, $form_state);
  81. }
  82. // If the widget is handling multiple values (e.g Options), or if we are
  83. // displaying an individual element, just get a single form element and make
  84. // it the $delta value.
  85. else {
  86. $delta = isset($get_delta) ? $get_delta : 0;
  87. $function = $instance['widget']['module'] . '_field_widget_form';
  88. if (function_exists($function)) {
  89. $element = array(
  90. '#entity' => $entity,
  91. '#entity_type' => $instance['entity_type'],
  92. '#bundle' => $instance['bundle'],
  93. '#field_name' => $field_name,
  94. '#language' => $langcode,
  95. '#field_parents' => $parents,
  96. '#columns' => array_keys($field['columns']),
  97. '#title' => check_plain($instance['label']),
  98. '#description' => field_filter_xss($instance['description']),
  99. // Only the first widget should be required.
  100. '#required' => $delta == 0 && $instance['required'],
  101. '#delta' => $delta,
  102. );
  103. if ($element = $function($form, $form_state, $field, $instance, $langcode, $items, $delta, $element)) {
  104. // Allow modules to alter the field widget form element.
  105. $context = array(
  106. 'form' => $form,
  107. 'field' => $field,
  108. 'instance' => $instance,
  109. 'langcode' => $langcode,
  110. 'items' => $items,
  111. 'delta' => $delta,
  112. );
  113. drupal_alter(array('field_widget_form', 'field_widget_' . $instance['widget']['type'] . '_form'), $element, $form_state, $context);
  114. // If we're processing a specific delta value for a field where the
  115. // field module handles multiples, set the delta in the result.
  116. // For fields that handle their own processing, we can't make
  117. // assumptions about how the field is structured, just merge in the
  118. // returned element.
  119. if (field_behaviors_widget('multiple values', $instance) == FIELD_BEHAVIOR_DEFAULT) {
  120. $elements[$delta] = $element;
  121. }
  122. else {
  123. $elements = $element;
  124. }
  125. }
  126. }
  127. }
  128. // Also aid in theming of field widgets by rendering a classified container.
  129. $addition[$field_name] = array(
  130. '#type' => 'container',
  131. '#attributes' => array(
  132. 'class' => array(
  133. 'field-type-' . drupal_html_class($field['type']),
  134. 'field-name-' . drupal_html_class($field_name),
  135. 'field-widget-' . drupal_html_class($instance['widget']['type']),
  136. ),
  137. ),
  138. '#weight' => $instance['widget']['weight'],
  139. );
  140. // Populate the 'array_parents' information in $form_state['field'] after
  141. // the form is built, so that we catch changes in the form structure performed
  142. // in alter() hooks.
  143. $elements['#after_build'][] = 'field_form_element_after_build';
  144. $elements['#field_name'] = $field_name;
  145. $elements['#language'] = $langcode;
  146. $elements['#field_parents'] = $parents;
  147. $addition[$field_name] += array(
  148. '#tree' => TRUE,
  149. // The '#language' key can be used to access the field's form element
  150. // when $langcode is unknown.
  151. '#language' => $langcode,
  152. $langcode => $elements,
  153. '#access' => field_access('edit', $field, $entity_type, $entity),
  154. );
  155. return $addition;
  156. }
  157. /**
  158. * Special handling to create form elements for multiple values.
  159. *
  160. * Handles generic features for multiple fields:
  161. * - number of widgets
  162. * - AHAH-'add more' button
  163. * - drag-n-drop value reordering
  164. */
  165. function field_multiple_value_form($field, $instance, $langcode, $items, &$form, &$form_state) {
  166. $field_name = $field['field_name'];
  167. $parents = $form['#parents'];
  168. // Determine the number of widgets to display.
  169. switch ($field['cardinality']) {
  170. case FIELD_CARDINALITY_UNLIMITED:
  171. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  172. $max = $field_state['items_count'];
  173. break;
  174. default:
  175. $max = $field['cardinality'] - 1;
  176. break;
  177. }
  178. $title = check_plain($instance['label']);
  179. $description = field_filter_xss($instance['description']);
  180. $id_prefix = implode('-', array_merge($parents, array($field_name)));
  181. $wrapper_id = drupal_html_id($id_prefix . '-add-more-wrapper');
  182. $field_elements = array();
  183. $function = $instance['widget']['module'] . '_field_widget_form';
  184. if (function_exists($function)) {
  185. for ($delta = 0; $delta <= $max; $delta++) {
  186. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  187. $element = array(
  188. '#entity_type' => $instance['entity_type'],
  189. '#entity' => $form['#entity'],
  190. '#bundle' => $instance['bundle'],
  191. '#field_name' => $field_name,
  192. '#language' => $langcode,
  193. '#field_parents' => $parents,
  194. '#columns' => array_keys($field['columns']),
  195. '#title' => $title,
  196. '#description' => $description,
  197. // Only the first widget should be required.
  198. '#required' => $delta == 0 && $instance['required'],
  199. '#delta' => $delta,
  200. '#weight' => $delta,
  201. );
  202. // For multiple fields, title and description are handled by the wrapping
  203. // table.
  204. if ($multiple) {
  205. if ($delta == 0) {
  206. $element['#title'] = $title;
  207. }
  208. else {
  209. $element['#title'] = t('!title (value @number)', array('@number' => $delta + 1, '!title' => $title));
  210. }
  211. $element['#title_display'] = 'invisible';
  212. $element['#description'] = '';
  213. }
  214. if ($element = $function($form, $form_state, $field, $instance, $langcode, $items, $delta, $element)) {
  215. // Input field for the delta (drag-n-drop reordering).
  216. if ($multiple) {
  217. // We name the element '_weight' to avoid clashing with elements
  218. // defined by widget.
  219. $element['_weight'] = array(
  220. '#type' => 'weight',
  221. '#title' => t('Weight for row @number', array('@number' => $delta + 1)),
  222. '#title_display' => 'invisible',
  223. // Note: this 'delta' is the FAPI 'weight' element's property.
  224. '#delta' => $max,
  225. '#default_value' => isset($items[$delta]['_weight']) ? $items[$delta]['_weight'] : $delta,
  226. '#weight' => 100,
  227. );
  228. }
  229. // Allow modules to alter the field widget form element.
  230. $context = array(
  231. 'form' => $form,
  232. 'field' => $field,
  233. 'instance' => $instance,
  234. 'langcode' => $langcode,
  235. 'items' => $items,
  236. 'delta' => $delta,
  237. );
  238. drupal_alter(array('field_widget_form', 'field_widget_' . $instance['widget']['type'] . '_form'), $element, $form_state, $context);
  239. $field_elements[$delta] = $element;
  240. }
  241. }
  242. if ($field_elements) {
  243. $field_elements += array(
  244. '#theme' => 'field_multiple_value_form',
  245. '#field_name' => $field['field_name'],
  246. '#cardinality' => $field['cardinality'],
  247. '#title' => $title,
  248. '#required' => $instance['required'],
  249. '#description' => $description,
  250. '#prefix' => '<div id="' . $wrapper_id . '">',
  251. '#suffix' => '</div>',
  252. '#max_delta' => $max,
  253. );
  254. // Add 'add more' button, if not working with a programmed form.
  255. if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED && empty($form_state['programmed'])) {
  256. $field_elements['add_more'] = array(
  257. '#type' => 'submit',
  258. '#name' => strtr($id_prefix, '-', '_') . '_add_more',
  259. '#value' => t('Add another item'),
  260. '#attributes' => array('class' => array('field-add-more-submit')),
  261. '#limit_validation_errors' => array(array_merge($parents, array($field_name, $langcode))),
  262. '#submit' => array('field_add_more_submit'),
  263. '#ajax' => array(
  264. 'callback' => 'field_add_more_js',
  265. 'wrapper' => $wrapper_id,
  266. 'effect' => 'fade',
  267. ),
  268. );
  269. }
  270. }
  271. }
  272. return $field_elements;
  273. }
  274. /**
  275. * Returns HTML for an individual form element.
  276. *
  277. * Combine multiple values into a table with drag-n-drop reordering.
  278. * TODO : convert to a template.
  279. *
  280. * @param $variables
  281. * An associative array containing:
  282. * - element: A render element representing the form element.
  283. *
  284. * @ingroup themeable
  285. */
  286. function theme_field_multiple_value_form($variables) {
  287. $element = $variables['element'];
  288. $output = '';
  289. if ($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
  290. $table_id = drupal_html_id($element['#field_name'] . '_values');
  291. $order_class = $element['#field_name'] . '-delta-order';
  292. $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';
  293. $header = array(
  294. array(
  295. 'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",
  296. 'colspan' => 2,
  297. 'class' => array('field-label'),
  298. ),
  299. t('Order'),
  300. );
  301. $rows = array();
  302. // Sort items according to '_weight' (needed when the form comes back after
  303. // preview or failed validation)
  304. $items = array();
  305. foreach (element_children($element) as $key) {
  306. if ($key === 'add_more') {
  307. $add_more_button = &$element[$key];
  308. }
  309. else {
  310. $items[] = &$element[$key];
  311. }
  312. }
  313. usort($items, '_field_sort_items_value_helper');
  314. // Add the items as table rows.
  315. foreach ($items as $key => $item) {
  316. $item['_weight']['#attributes']['class'] = array($order_class);
  317. $delta_element = drupal_render($item['_weight']);
  318. $cells = array(
  319. array('data' => '', 'class' => array('field-multiple-drag')),
  320. drupal_render($item),
  321. array('data' => $delta_element, 'class' => array('delta-order')),
  322. );
  323. $rows[] = array(
  324. 'data' => $cells,
  325. 'class' => array('draggable'),
  326. );
  327. }
  328. $output = '<div class="form-item">';
  329. $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
  330. $output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
  331. $output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
  332. $output .= '</div>';
  333. drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  334. }
  335. else {
  336. foreach (element_children($element) as $key) {
  337. $output .= drupal_render($element[$key]);
  338. }
  339. }
  340. return $output;
  341. }
  342. /**
  343. * #after_build callback for field elements in a form.
  344. *
  345. * This stores the final location of the field within the form structure so
  346. * that field_default_form_errors() can assign validation errors to the right
  347. * form element.
  348. *
  349. * @see field_default_form_errors()
  350. */
  351. function field_form_element_after_build($element, &$form_state) {
  352. $parents = $element['#field_parents'];
  353. $field_name = $element['#field_name'];
  354. $langcode = $element['#language'];
  355. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  356. $field_state['array_parents'] = $element['#array_parents'];
  357. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  358. return $element;
  359. }
  360. /**
  361. * Transfer field-level validation errors to widgets.
  362. */
  363. function field_default_form_errors($entity_type, $entity, $field, $instance, $langcode, $items, $form, &$form_state) {
  364. $field_state = field_form_get_state($form['#parents'], $field['field_name'], $langcode, $form_state);
  365. if (!empty($field_state['errors'])) {
  366. // Locate the correct element in the form.
  367. $element = drupal_array_get_nested_value($form_state['complete form'], $field_state['array_parents']);
  368. // Only set errors if the element is accessible.
  369. if (!isset($element['#access']) || $element['#access']) {
  370. $function = $instance['widget']['module'] . '_field_widget_error';
  371. $function_exists = function_exists($function);
  372. $multiple_widget = field_behaviors_widget('multiple values', $instance) != FIELD_BEHAVIOR_DEFAULT;
  373. foreach ($field_state['errors'] as $delta => $delta_errors) {
  374. // For multiple single-value widgets, pass errors by delta.
  375. // For a multiple-value widget, pass all errors to the main widget.
  376. $error_element = $multiple_widget ? $element : $element[$delta];
  377. foreach ($delta_errors as $error) {
  378. if ($function_exists) {
  379. $function($error_element, $error, $form, $form_state);
  380. }
  381. else {
  382. // Make sure that errors are reported (even incorrectly flagged) if
  383. // the widget module fails to implement hook_field_widget_error().
  384. form_error($error_element, $error['message']);
  385. }
  386. }
  387. }
  388. // Reinitialize the errors list for the next submit.
  389. $field_state['errors'] = array();
  390. field_form_set_state($form['#parents'], $field['field_name'], $langcode, $form_state, $field_state);
  391. }
  392. }
  393. }
  394. /**
  395. * Submit handler for the "Add another item" button of a field form.
  396. *
  397. * This handler is run regardless of whether JS is enabled or not. It makes
  398. * changes to the form state. If the button was clicked with JS disabled, then
  399. * the page is reloaded with the complete rebuilt form. If the button was
  400. * clicked with JS enabled, then ajax_form_callback() calls field_add_more_js()
  401. * to return just the changed part of the form.
  402. */
  403. function field_add_more_submit($form, &$form_state) {
  404. $button = $form_state['triggering_element'];
  405. // Go one level up in the form, to the widgets container.
  406. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  407. $field_name = $element['#field_name'];
  408. $langcode = $element['#language'];
  409. $parents = $element['#field_parents'];
  410. // Increment the items count.
  411. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  412. $field_state['items_count']++;
  413. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  414. $form_state['rebuild'] = TRUE;
  415. }
  416. /**
  417. * Ajax callback in response to a new empty widget being added to the form.
  418. *
  419. * This returns the new page content to replace the page content made obsolete
  420. * by the form submission.
  421. *
  422. * @see field_add_more_submit()
  423. */
  424. function field_add_more_js($form, $form_state) {
  425. $button = $form_state['triggering_element'];
  426. // Go one level up in the form, to the widgets container.
  427. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  428. $field_name = $element['#field_name'];
  429. $langcode = $element['#language'];
  430. $parents = $element['#field_parents'];
  431. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  432. $field = $field_state['field'];
  433. if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED) {
  434. return;
  435. }
  436. // Add a DIV around the delta receiving the Ajax effect.
  437. $delta = $element['#max_delta'];
  438. $element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
  439. $element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';
  440. return $element;
  441. }
  442. /**
  443. * Retrieves processing information about a field from $form_state.
  444. *
  445. * @param $parents
  446. * The array of #parents where the field lives in the form.
  447. * @param $field_name
  448. * The field name.
  449. * @param $langcode
  450. * The language in which the field values are entered.
  451. * @param $form_state
  452. * The form state.
  453. *
  454. * @return
  455. * An array with the following key/data pairs:
  456. * - field: the field definition array,
  457. * - instance: the field instance definition array,
  458. * - items_count: the number of widgets to display for the field,
  459. * - array_parents: the location of the field's widgets within the $form
  460. * structure. This entry is populated at '#after_build' time.
  461. * - errors: the array of field validation errors reported on the field. This
  462. * entry is populated at field_attach_form_validate() time.
  463. *
  464. * @see field_form_set_state()
  465. */
  466. function field_form_get_state($parents, $field_name, $langcode, &$form_state) {
  467. $form_state_parents = _field_form_state_parents($parents, $field_name, $langcode);
  468. return drupal_array_get_nested_value($form_state, $form_state_parents);
  469. }
  470. /**
  471. * Stores processing information about a field in $form_state.
  472. *
  473. * @param $parents
  474. * The array of #parents where the field lives in the form.
  475. * @param $field_name
  476. * The field name.
  477. * @param $langcode
  478. * The language in which the field values are entered.
  479. * @param $form_state
  480. * The form state.
  481. * @param $field_state
  482. * The array of data to store. See field_form_get_state() for the structure
  483. * and content of the array.
  484. *
  485. * @see field_form_get_state()
  486. */
  487. function field_form_set_state($parents, $field_name, $langcode, &$form_state, $field_state) {
  488. $form_state_parents = _field_form_state_parents($parents, $field_name, $langcode);
  489. drupal_array_set_nested_value($form_state, $form_state_parents, $field_state);
  490. }
  491. /**
  492. * Returns the location of processing information within $form_state.
  493. */
  494. function _field_form_state_parents($parents, $field_name, $langcode) {
  495. // To ensure backwards compatibility on regular entity forms for widgets that
  496. // still access $form_state['field'][$field_name] directly,
  497. // - top-level fields (empty $parents) are placed directly under
  498. // $form_state['fields'][$field_name].
  499. // - Other fields are placed under
  500. // $form_state['field']['#parents'][...$parents...]['#fields'][$field_name]
  501. // to avoid clashes between field names and $parents parts.
  502. // @todo Remove backwards compatibility in Drupal 8, and use a unique
  503. // $form_state['field'][...$parents...]['#fields'][$field_name] structure.
  504. if (!empty($parents)) {
  505. $form_state_parents = array_merge(array('#parents'), $parents, array('#fields'));
  506. }
  507. else {
  508. $form_state_parents = array();
  509. }
  510. $form_state_parents = array_merge(array('field'), $form_state_parents, array($field_name, $langcode));
  511. return $form_state_parents;
  512. }
  513. /**
  514. * Retrieves the field definition for a widget's helper callbacks.
  515. *
  516. * Widgets helper element callbacks (such as #process, #element_validate,
  517. * #value_callback, ...) should use field_widget_field() and
  518. * field_widget_instance() instead of field_info_field() and
  519. * field_info_instance() when they need to access field or instance properties.
  520. * See hook_field_widget_form() for more details.
  521. *
  522. * @param $element
  523. * The structured array for the widget.
  524. * @param $form_state
  525. * The form state.
  526. *
  527. * @return
  528. * The $field definition array for the current widget.
  529. *
  530. * @see field_widget_instance()
  531. * @see hook_field_widget_form()
  532. */
  533. function field_widget_field($element, $form_state) {
  534. $field_state = field_form_get_state($element['#field_parents'], $element['#field_name'], $element['#language'], $form_state);
  535. return $field_state['field'];
  536. }
  537. /**
  538. * Retrieves the instance definition array for a widget's helper callbacks.
  539. *
  540. * Widgets helper element callbacks (such as #process, #element_validate,
  541. * #value_callback, ...) should use field_widget_field() and
  542. * field_widget_instance() instead of field_info_field() and
  543. * field_info_instance() when they need to access field or instance properties.
  544. * See hook_field_widget_form() for more details.
  545. *
  546. * @param $element
  547. * The structured array for the widget.
  548. * @param $form_state
  549. * The form state.
  550. *
  551. * @return
  552. * The $instance definition array for the current widget.
  553. *
  554. * @see field_widget_field()
  555. * @see hook_field_widget_form()
  556. */
  557. function field_widget_instance($element, $form_state) {
  558. $field_state = field_form_get_state($element['#field_parents'], $element['#field_name'], $element['#language'], $form_state);
  559. return $field_state['instance'];
  560. }