field.form.inc

  1. drupal
    1. 7 modules/field/field.form.inc
    2. 8 core/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

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