field.form.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. // 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. // For multiple fields, title and description are handled by the wrapping table.
  196. '#title' => $multiple ? '' : $title,
  197. '#description' => $multiple ? '' : $description,
  198. // Only the first widget should be required.
  199. '#required' => $delta == 0 && $instance['required'],
  200. '#delta' => $delta,
  201. '#weight' => $delta,
  202. );
  203. if ($element = $function($form, $form_state, $field, $instance, $langcode, $items, $delta, $element)) {
  204. // Input field for the delta (drag-n-drop reordering).
  205. if ($multiple) {
  206. // We name the element '_weight' to avoid clashing with elements
  207. // defined by widget.
  208. $element['_weight'] = array(
  209. '#type' => 'weight',
  210. '#title' => t('Weight for row @number', array('@number' => $delta + 1)),
  211. '#title_display' => 'invisible',
  212. // Note: this 'delta' is the FAPI 'weight' element's property.
  213. '#delta' => $max,
  214. '#default_value' => isset($items[$delta]['_weight']) ? $items[$delta]['_weight'] : $delta,
  215. '#weight' => 100,
  216. );
  217. }
  218. // Allow modules to alter the field widget form element.
  219. $context = array(
  220. 'form' => $form,
  221. 'field' => $field,
  222. 'instance' => $instance,
  223. 'langcode' => $langcode,
  224. 'items' => $items,
  225. 'delta' => $delta,
  226. );
  227. drupal_alter(array('field_widget_form', 'field_widget_' . $instance['widget']['type'] . '_form'), $element, $form_state, $context);
  228. $field_elements[$delta] = $element;
  229. }
  230. }
  231. if ($field_elements) {
  232. $field_elements += array(
  233. '#theme' => 'field_multiple_value_form',
  234. '#field_name' => $field['field_name'],
  235. '#cardinality' => $field['cardinality'],
  236. '#title' => $title,
  237. '#required' => $instance['required'],
  238. '#description' => $description,
  239. '#prefix' => '<div id="' . $wrapper_id . '">',
  240. '#suffix' => '</div>',
  241. '#max_delta' => $max,
  242. );
  243. // Add 'add more' button, if not working with a programmed form.
  244. if ($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED && empty($form_state['programmed'])) {
  245. $field_elements['add_more'] = array(
  246. '#type' => 'submit',
  247. '#name' => strtr($id_prefix, '-', '_') . '_add_more',
  248. '#value' => t('Add another item'),
  249. '#attributes' => array('class' => array('field-add-more-submit')),
  250. '#limit_validation_errors' => array(array_merge($parents, array($field_name, $langcode))),
  251. '#submit' => array('field_add_more_submit'),
  252. '#ajax' => array(
  253. 'callback' => 'field_add_more_js',
  254. 'wrapper' => $wrapper_id,
  255. 'effect' => 'fade',
  256. ),
  257. );
  258. }
  259. }
  260. }
  261. return $field_elements;
  262. }
  263. /**
  264. * Returns HTML for an individual form element.
  265. *
  266. * Combine multiple values into a table with drag-n-drop reordering.
  267. * TODO : convert to a template.
  268. *
  269. * @param $variables
  270. * An associative array containing:
  271. * - element: A render element representing the form element.
  272. *
  273. * @ingroup themeable
  274. */
  275. function theme_field_multiple_value_form($variables) {
  276. $element = $variables['element'];
  277. $output = '';
  278. if ($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
  279. $table_id = drupal_html_id($element['#field_name'] . '_values');
  280. $order_class = $element['#field_name'] . '-delta-order';
  281. $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';
  282. $header = array(
  283. array(
  284. 'data' => '<label>' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "</label>",
  285. 'colspan' => 2,
  286. 'class' => array('field-label'),
  287. ),
  288. t('Order'),
  289. );
  290. $rows = array();
  291. // Sort items according to '_weight' (needed when the form comes back after
  292. // preview or failed validation)
  293. $items = array();
  294. foreach (element_children($element) as $key) {
  295. if ($key === 'add_more') {
  296. $add_more_button = &$element[$key];
  297. }
  298. else {
  299. $items[] = &$element[$key];
  300. }
  301. }
  302. usort($items, '_field_sort_items_value_helper');
  303. // Add the items as table rows.
  304. foreach ($items as $key => $item) {
  305. $item['_weight']['#attributes']['class'] = array($order_class);
  306. $delta_element = drupal_render($item['_weight']);
  307. $cells = array(
  308. array('data' => '', 'class' => array('field-multiple-drag')),
  309. drupal_render($item),
  310. array('data' => $delta_element, 'class' => array('delta-order')),
  311. );
  312. $rows[] = array(
  313. 'data' => $cells,
  314. 'class' => array('draggable'),
  315. );
  316. }
  317. $output = '<div class="form-item">';
  318. $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
  319. $output .= $element['#description'] ? '<div class="description">' . $element['#description'] . '</div>' : '';
  320. $output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
  321. $output .= '</div>';
  322. drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  323. }
  324. else {
  325. foreach (element_children($element) as $key) {
  326. $output .= drupal_render($element[$key]);
  327. }
  328. }
  329. return $output;
  330. }
  331. /**
  332. * #after_build callback for field elements in a form.
  333. *
  334. * This stores the final location of the field within the form structure so
  335. * that field_default_form_errors() can assign validation errors to the right
  336. * form element.
  337. *
  338. * @see field_default_form_errors()
  339. */
  340. function field_form_element_after_build($element, &$form_state) {
  341. $parents = $element['#field_parents'];
  342. $field_name = $element['#field_name'];
  343. $langcode = $element['#language'];
  344. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  345. $field_state['array_parents'] = $element['#array_parents'];
  346. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  347. return $element;
  348. }
  349. /**
  350. * Transfer field-level validation errors to widgets.
  351. */
  352. function field_default_form_errors($entity_type, $entity, $field, $instance, $langcode, $items, $form, &$form_state) {
  353. $field_state = field_form_get_state($form['#parents'], $field['field_name'], $langcode, $form_state);
  354. if (!empty($field_state['errors'])) {
  355. // Locate the correct element in the form.
  356. $element = drupal_array_get_nested_value($form_state['complete form'], $field_state['array_parents']);
  357. // Only set errors if the element is accessible.
  358. if (!isset($element['#access']) || $element['#access']) {
  359. $function = $instance['widget']['module'] . '_field_widget_error';
  360. $function_exists = function_exists($function);
  361. $multiple_widget = field_behaviors_widget('multiple values', $instance) != FIELD_BEHAVIOR_DEFAULT;
  362. foreach ($field_state['errors'] as $delta => $delta_errors) {
  363. // For multiple single-value widgets, pass errors by delta.
  364. // For a multiple-value widget, pass all errors to the main widget.
  365. $error_element = $multiple_widget ? $element : $element[$delta];
  366. foreach ($delta_errors as $error) {
  367. if ($function_exists) {
  368. $function($error_element, $error, $form, $form_state);
  369. }
  370. else {
  371. // Make sure that errors are reported (even incorrectly flagged) if
  372. // the widget module fails to implement hook_field_widget_error().
  373. form_error($error_element, $error['message']);
  374. }
  375. }
  376. }
  377. // Reinitialize the errors list for the next submit.
  378. $field_state['errors'] = array();
  379. field_form_set_state($form['#parents'], $field['field_name'], $langcode, $form_state, $field_state);
  380. }
  381. }
  382. }
  383. /**
  384. * Submit handler for the "Add another item" button of a field form.
  385. *
  386. * This handler is run regardless of whether JS is enabled or not. It makes
  387. * changes to the form state. If the button was clicked with JS disabled, then
  388. * the page is reloaded with the complete rebuilt form. If the button was
  389. * clicked with JS enabled, then ajax_form_callback() calls field_add_more_js()
  390. * to return just the changed part of the form.
  391. */
  392. function field_add_more_submit($form, &$form_state) {
  393. $button = $form_state['triggering_element'];
  394. // Go one level up in the form, to the widgets container.
  395. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  396. $field_name = $element['#field_name'];
  397. $langcode = $element['#language'];
  398. $parents = $element['#field_parents'];
  399. // Increment the items count.
  400. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  401. $field_state['items_count']++;
  402. field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
  403. $form_state['rebuild'] = TRUE;
  404. }
  405. /**
  406. * Ajax callback in response to a new empty widget being added to the form.
  407. *
  408. * This returns the new page content to replace the page content made obsolete
  409. * by the form submission.
  410. *
  411. * @see field_add_more_submit()
  412. */
  413. function field_add_more_js($form, $form_state) {
  414. $button = $form_state['triggering_element'];
  415. // Go one level up in the form, to the widgets container.
  416. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  417. $field_name = $element['#field_name'];
  418. $langcode = $element['#language'];
  419. $parents = $element['#field_parents'];
  420. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  421. $field = $field_state['field'];
  422. if ($field['cardinality'] != FIELD_CARDINALITY_UNLIMITED) {
  423. return;
  424. }
  425. // Add a DIV around the delta receiving the Ajax effect.
  426. $delta = $element['#max_delta'];
  427. $element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
  428. $element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';
  429. return $element;
  430. }
  431. /**
  432. * Retrieves processing information about a field from $form_state.
  433. *
  434. * @param $parents
  435. * The array of #parents where the field lives in the form.
  436. * @param $field_name
  437. * The field name.
  438. * @param $langcode
  439. * The language in which the field values are entered.
  440. * @param $form_state
  441. * The form state.
  442. *
  443. * @return
  444. * An array with the following key/data pairs:
  445. * - field: the field definition array,
  446. * - instance: the field instance definition array,
  447. * - items_count: the number of widgets to display for the field,
  448. * - array_parents: the location of the field's widgets within the $form
  449. * structure. This entry is populated at '#after_build' time.
  450. * - errors: the array of field validation errors reported on the field. This
  451. * entry is populated at field_attach_form_validate() time.
  452. *
  453. * @see field_form_set_state()
  454. */
  455. function field_form_get_state($parents, $field_name, $langcode, &$form_state) {
  456. $form_state_parents = _field_form_state_parents($parents, $field_name, $langcode);
  457. return drupal_array_get_nested_value($form_state, $form_state_parents);
  458. }
  459. /**
  460. * Stores processing information about a field in $form_state.
  461. *
  462. * @param $parents
  463. * The array of #parents where the field lives in the form.
  464. * @param $field_name
  465. * The field name.
  466. * @param $langcode
  467. * The language in which the field values are entered.
  468. * @param $form_state
  469. * The form state.
  470. * @param $field_state
  471. * The array of data to store. See field_form_get_state() for the structure
  472. * and content of the array.
  473. *
  474. * @see field_form_get_state()
  475. */
  476. function field_form_set_state($parents, $field_name, $langcode, &$form_state, $field_state) {
  477. $form_state_parents = _field_form_state_parents($parents, $field_name, $langcode);
  478. drupal_array_set_nested_value($form_state, $form_state_parents, $field_state);
  479. }
  480. /**
  481. * Returns the location of processing information within $form_state.
  482. */
  483. function _field_form_state_parents($parents, $field_name, $langcode) {
  484. // To ensure backwards compatibility on regular entity forms for widgets that
  485. // still access $form_state['field'][$field_name] directly,
  486. // - top-level fields (empty $parents) are placed directly under
  487. // $form_state['fields'][$field_name].
  488. // - Other fields are placed under
  489. // $form_state['field']['#parents'][...$parents...]['#fields'][$field_name]
  490. // to avoid clashes between field names and $parents parts.
  491. // @todo Remove backwards compatibility in Drupal 8, and use a unique
  492. // $form_state['field'][...$parents...]['#fields'][$field_name] structure.
  493. if (!empty($parents)) {
  494. $form_state_parents = array_merge(array('#parents'), $parents, array('#fields'));
  495. }
  496. else {
  497. $form_state_parents = array();
  498. }
  499. $form_state_parents = array_merge(array('field'), $form_state_parents, array($field_name, $langcode));
  500. return $form_state_parents;
  501. }
  502. /**
  503. * Retrieves the field definition for a widget's helper callbacks.
  504. *
  505. * Widgets helper element callbacks (such as #process, #element_validate,
  506. * #value_callback, ...) should use field_widget_field() and
  507. * field_widget_instance() instead of field_info_field() and
  508. * field_info_instance() when they need to access field or instance properties.
  509. * See hook_field_widget_form() for more details.
  510. *
  511. * @param $element
  512. * The structured array for the widget.
  513. * @param $form_state
  514. * The form state.
  515. *
  516. * @return
  517. * The $field definition array for the current widget.
  518. *
  519. * @see field_widget_instance()
  520. * @see hook_field_widget_form()
  521. */
  522. function field_widget_field($element, $form_state) {
  523. $field_state = field_form_get_state($element['#field_parents'], $element['#field_name'], $element['#language'], $form_state);
  524. return $field_state['field'];
  525. }
  526. /**
  527. * Retrieves the instance definition array for a widget's helper callbacks.
  528. *
  529. * Widgets helper element callbacks (such as #process, #element_validate,
  530. * #value_callback, ...) should use field_widget_field() and
  531. * field_widget_instance() instead of field_info_field() and
  532. * field_info_instance() when they need to access field or instance properties.
  533. * See hook_field_widget_form() for more details.
  534. *
  535. * @param $element
  536. * The structured array for the widget.
  537. * @param $form_state
  538. * The form state.
  539. *
  540. * @return
  541. * The $instance definition array for the current widget.
  542. *
  543. * @see field_widget_field()
  544. * @see hook_field_widget_form()
  545. */
  546. function field_widget_instance($element, $form_state) {
  547. $field_state = field_form_get_state($element['#field_parents'], $element['#field_name'], $element['#language'], $form_state);
  548. return $field_state['instance'];
  549. }