Skip navigation
Help

field.form.inc

  1. drupal
    1. 7 drupal/modules/field/field.form.inc

Field forms management.

Functions & methods

NameDescription
field_add_more_jsAjax callback in response to a new empty widget being added to the form.
field_add_more_submitSubmit handler for the "Add another item" button of a field form.
field_default_formCreate a separate form element for each field.
field_default_form_errorsTransfer field-level validation errors to widgets.
field_form_element_after_build#after_build callback for field elements in a form.
field_form_get_stateRetrieves processing information about a field from $form_state.
field_form_set_stateStores processing information about a field in $form_state.
field_multiple_value_formSpecial handling to create form elements for multiple values.
field_widget_fieldRetrieves the field definition for a widget's helper callbacks.
field_widget_instanceRetrieves the instance definition array for a widget's helper callbacks.
theme_field_multiple_value_formReturns HTML for an individual form element.
_field_form_state_parentsReturns the location of processing information within $form_state.

File

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