field.form.inc 21 KB

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