form.inc

  1. Views
    1. 6 includes/form.inc
  2. drupal
    1. 4.7 includes/form.inc
    2. 5 includes/form.inc
    3. 6 includes/form.inc
    4. 7 includes/form.inc
    5. 8 core/includes/form.inc

Functions for form and batch generation and processing.

Functions & methods

NameDescription
batch_getRetrieves the current batch.
batch_processProcesses the batch.
batch_setAdds a new batch.
date_validateValidates the date type to prevent invalid dates (e.g., February 30, 2006).
drupal_build_formBuilds and process a form based on a form id.
drupal_form_submitRetrieves, populates, and processes a form.
drupal_get_formReturns a renderable form array for a given form ID.
drupal_prepare_formPrepares a structured form array.
drupal_process_formProcesses a form submission.
drupal_rebuild_formConstructs a new $form from the information in $form_state.
drupal_redirect_formRedirects the user to a URL after a form has been processed.
drupal_retrieve_formRetrieves the structured array that defines a given form.
drupal_validate_formValidates user-submitted form data in the $form_state array.
element_validate_integerForm element validation handler for integer elements.
element_validate_integer_positiveForm element validation handler for integer elements that must be positive.
element_validate_numberForm element validation handler for number elements.
form_builderBuilds and processes all elements in the structured form array.
form_clear_errorClears all errors against all form elements made by form_set_error().
form_errorFlags an element as having an error.
form_execute_handlersExecutes custom validation and submission handlers for a given form.
form_get_cacheFetches a form from cache.
form_get_errorReturns the error message filed against the given form element.
form_get_errorsReturns an associative array of all errors.
form_get_optionsReturns the indexes of a select element's options matching a given key.
form_load_includeEnsures an include file is loaded loaded whenever the form is processed.
form_options_flattenAllows PHP array processing of multiple select options with the same value.
form_pre_render_conditional_form_elementAdds form element theming to an element if its title or description is set.
form_pre_render_fieldsetAdds members of this group as actual elements for rendering.
form_process_actionsProcesses a form actions container element.
form_process_checkboxSets the #checked property of a checkbox element.
form_process_checkboxesProcesses a checkboxes form element.
form_process_containerProcesses a container element.
form_process_dateExpands a date element into year, month, and day select elements.
form_process_fieldsetArranges fieldsets into groups.
form_process_machine_nameProcesses a machine-readable name form element.
form_process_password_confirmExpand a password_confirm field into two text boxes.
form_process_radiosExpands a radios element into individual radio elements.
form_process_selectProcesses a select list form element.
form_process_tableselectCreates checkbox or radio elements to populate a tableselect table.
form_process_vertical_tabsCreates a group formatted as vertical tabs.
form_process_weightExpands a weight element into a select element.
form_select_optionsConverts a select form element's options array into HTML.
form_set_cacheStores a form in the cache.
form_set_errorFiles an error against a form element.
form_set_valueChanges submitted form values during form validation.
form_state_defaultsRetrieves default values for the $form_state array.
form_state_keys_no_cacheReturns an array of $form_state keys that shouldn't be cached.
form_state_values_cleanRemoves internal Form API elements and buttons from submitted form values.
form_type_checkboxes_valueDetermines the value for a checkboxes form element.
form_type_checkbox_valueDetermines the value for a checkbox form element.
form_type_image_button_valueDetermines the value for an image button form element.
form_type_password_confirm_valueDetermines the value for a password_confirm form element.
form_type_radios_valueForm value callback: Determines the value for a #type radios form element.
form_type_select_valueDetermines the value for a select form element.
form_type_tableselect_valueDetermines the value for a tableselect form element.
form_type_textfield_valueDetermines the value for a textfield form element.
form_type_token_valueDetermines the value for form's token value.
form_validate_machine_nameForm element validation handler for machine_name elements.
map_monthHelper function for usage with drupal_map_assoc to display month names.
password_confirm_validateValidates a password_confirm element.
theme_buttonReturns HTML for a button form element.
theme_checkboxReturns HTML for a checkbox form element.
theme_checkboxesReturns HTML for a set of checkbox form elements.
theme_containerReturns HTML to wrap child elements in a container.
theme_dateReturns HTML for a date selection form element.
theme_fieldsetReturns HTML for a fieldset form element and its children.
theme_fileReturns HTML for a file upload form element.
theme_formReturns HTML for a form.
theme_form_elementReturns HTML for a form element.
theme_form_element_labelReturns HTML for a form element label and required marker.
theme_form_required_markerReturns HTML for a marker for required form elements.
theme_hiddenReturns HTML for a hidden form element.
theme_image_buttonReturns HTML for an image button form element.
theme_passwordReturns HTML for a password form element.
theme_radioReturns HTML for a radio button form element.
theme_radiosReturns HTML for a set of radio button form elements.
theme_selectReturns HTML for a select form element.
theme_submitReturns HTML for a submit button form element.
theme_tableselectReturns HTML for a table with radio buttons or checkboxes.
theme_textareaReturns HTML for a textarea form element.
theme_textfieldReturns HTML for a textfield form element.
theme_vertical_tabsReturns HTML for an element's children fieldsets as vertical tabs.
weight_valueSets the value for a weight element, with zero as a default.
_batch_populate_queuePopulates a job queue with the operations of a batch set.
_batch_queueReturns a queue object for a batch set.
_form_builder_handle_input_elementAdds the #name and #value properties of an input element before rendering.
_form_button_was_clickedDetermines if a given button triggered the form submission.
_form_element_triggered_scripted_submissionDetects if an element triggered the form submission via Ajax.
_form_options_flattenIterates over an array and returns a flat array with duplicate keys removed.
_form_set_classSets a form element's class attribute.
_form_validatePerforms validation on form elements.

File

includes/form.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions for form and batch generation and processing.
  5. */
  6. /**
  7. * @defgroup forms Form builder functions
  8. * @{
  9. * Functions that build an abstract representation of a HTML form.
  10. *
  11. * All modules should declare their form builder functions to be in this
  12. * group and each builder function should reference its validate and submit
  13. * functions using \@see. Conversely, validate and submit functions should
  14. * reference the form builder function using \@see. For examples, of this see
  15. * system_modules_uninstall() or user_pass(), the latter of which has the
  16. * following in its doxygen documentation:
  17. *
  18. * \@ingroup forms
  19. * \@see user_pass_validate().
  20. * \@see user_pass_submit().
  21. *
  22. * @}
  23. */
  24. /**
  25. * @defgroup form_api Form generation
  26. * @{
  27. * Functions to enable the processing and display of HTML forms.
  28. *
  29. * Drupal uses these functions to achieve consistency in its form processing and
  30. * presentation, while simplifying code and reducing the amount of HTML that
  31. * must be explicitly generated by modules.
  32. *
  33. * The primary function used with forms is drupal_get_form(), which is
  34. * used for forms presented interactively to a user. Forms can also be built and
  35. * submitted programmatically without any user input using the
  36. * drupal_form_submit() function.
  37. *
  38. * drupal_get_form() handles retrieving, processing, and displaying a rendered
  39. * HTML form for modules automatically.
  40. *
  41. * Here is an example of how to use drupal_get_form() and a form builder
  42. * function:
  43. * @code
  44. * $form = drupal_get_form('my_module_example_form');
  45. * ...
  46. * function my_module_example_form($form, &$form_state) {
  47. * $form['submit'] = array(
  48. * '#type' => 'submit',
  49. * '#value' => t('Submit'),
  50. * );
  51. * return $form;
  52. * }
  53. * function my_module_example_form_validate($form, &$form_state) {
  54. * // Validation logic.
  55. * }
  56. * function my_module_example_form_submit($form, &$form_state) {
  57. * // Submission logic.
  58. * }
  59. * @endcode
  60. *
  61. * Or with any number of additional arguments:
  62. * @code
  63. * $extra = "extra";
  64. * $form = drupal_get_form('my_module_example_form', $extra);
  65. * ...
  66. * function my_module_example_form($form, &$form_state, $extra) {
  67. * $form['submit'] = array(
  68. * '#type' => 'submit',
  69. * '#value' => $extra,
  70. * );
  71. * return $form;
  72. * }
  73. * @endcode
  74. *
  75. * The $form argument to form-related functions is a structured array containing
  76. * the elements and properties of the form. For information on the array
  77. * components and format, and more detailed explanations of the Form API
  78. * workflow, see the
  79. * @link http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html Form API reference @endlink
  80. * and the
  81. * @link http://drupal.org/node/37775 Form API documentation section. @endlink
  82. * In addition, there is a set of Form API tutorials in
  83. * @link form_example_tutorial.inc the Form Example Tutorial @endlink which
  84. * provide basics all the way up through multistep forms.
  85. *
  86. * In the form builder, validation, submission, and other form functions,
  87. * $form_state is the primary influence on the processing of the form and is
  88. * passed by reference to most functions, so they use it to communicate with
  89. * the form system and each other.
  90. *
  91. * See drupal_build_form() for documentation of $form_state keys.
  92. */
  93. /**
  94. * Returns a renderable form array for a given form ID.
  95. *
  96. * This function should be used instead of drupal_build_form() when $form_state
  97. * is not needed (i.e., when initially rendering the form) and is often
  98. * used as a menu callback.
  99. *
  100. * @param $form_id
  101. * The unique string identifying the desired form. If a function with that
  102. * name exists, it is called to build the form array. Modules that need to
  103. * generate the same form (or very similar forms) using different $form_ids
  104. * can implement hook_forms(), which maps different $form_id values to the
  105. * proper form constructor function. Examples may be found in node_forms(),
  106. * and search_forms().
  107. * @param ...
  108. * Any additional arguments are passed on to the functions called by
  109. * drupal_get_form(), including the unique form constructor function. For
  110. * example, the node_edit form requires that a node object is passed in here
  111. * when it is called. These are available to implementations of
  112. * hook_form_alter() and hook_form_FORM_ID_alter() as the array
  113. * $form_state['build_info']['args'].
  114. *
  115. * @return
  116. * The form array.
  117. *
  118. * @see drupal_build_form()
  119. */
  120. function drupal_get_form($form_id) {
  121. $form_state = array();
  122. $args = func_get_args();
  123. // Remove $form_id from the arguments.
  124. array_shift($args);
  125. $form_state['build_info']['args'] = $args;
  126. return drupal_build_form($form_id, $form_state);
  127. }
  128. /**
  129. * Builds and process a form based on a form id.
  130. *
  131. * The form may also be retrieved from the cache if the form was built in a
  132. * previous page-load. The form is then passed on for processing, validation
  133. * and submission if there is proper input.
  134. *
  135. * @param $form_id
  136. * The unique string identifying the desired form. If a function with that
  137. * name exists, it is called to build the form array. Modules that need to
  138. * generate the same form (or very similar forms) using different $form_ids
  139. * can implement hook_forms(), which maps different $form_id values to the
  140. * proper form constructor function. Examples may be found in node_forms(),
  141. * and search_forms().
  142. * @param $form_state
  143. * An array which stores information about the form. This is passed as a
  144. * reference so that the caller can use it to examine what in the form changed
  145. * when the form submission process is complete. Furthermore, it may be used
  146. * to store information related to the processed data in the form, which will
  147. * persist across page requests when the 'cache' or 'rebuild' flag is set.
  148. * The following parameters may be set in $form_state to affect how the form
  149. * is rendered:
  150. * - build_info: Internal. An associative array of information stored by Form
  151. * API that is necessary to build and rebuild the form from cache when the
  152. * original context may no longer be available:
  153. * - args: A list of arguments to pass to the form constructor.
  154. * - files: An optional array defining include files that need to be loaded
  155. * for building the form. Each array entry may be the path to a file or
  156. * another array containing values for the parameters 'type', 'module' and
  157. * 'name' as needed by module_load_include(). The files listed here are
  158. * automatically loaded by form_get_cache(). By default the current menu
  159. * router item's 'file' definition is added, if any. Use
  160. * form_load_include() to add include files from a form constructor.
  161. * - base_form_id: Identification for a base form, as declared in a
  162. * hook_forms() implementation.
  163. * - rebuild_info: Internal. Similar to 'build_info', but pertaining to
  164. * drupal_rebuild_form().
  165. * - rebuild: Normally, after the entire form processing is completed and
  166. * submit handlers have run, a form is considered to be done and
  167. * drupal_redirect_form() will redirect the user to a new page using a GET
  168. * request (so a browser refresh does not re-submit the form). However, if
  169. * 'rebuild' has been set to TRUE, then a new copy of the form is
  170. * immediately built and sent to the browser, instead of a redirect. This is
  171. * used for multi-step forms, such as wizards and confirmation forms.
  172. * Normally, $form_state['rebuild'] is set by a submit handler, since it is
  173. * usually logic within a submit handler that determines whether a form is
  174. * done or requires another step. However, a validation handler may already
  175. * set $form_state['rebuild'] to cause the form processing to bypass submit
  176. * handlers and rebuild the form instead, even if there are no validation
  177. * errors.
  178. * - redirect: Used to redirect the form on submission. It may either be a
  179. * string containing the destination URL, or an array of arguments
  180. * compatible with drupal_goto(). See drupal_redirect_form() for complete
  181. * information.
  182. * - no_redirect: If set to TRUE the form will NOT perform a drupal_goto(),
  183. * even if 'redirect' is set.
  184. * - method: The HTTP form method to use for finding the input for this form.
  185. * May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method
  186. * forms do not use form ids so are always considered to be submitted, which
  187. * can have unexpected effects. The 'get' method should only be used on
  188. * forms that do not change data, as that is exclusively the domain of
  189. * 'post.'
  190. * - cache: If set to TRUE the original, unprocessed form structure will be
  191. * cached, which allows the entire form to be rebuilt from cache. A typical
  192. * form workflow involves two page requests; first, a form is built and
  193. * rendered for the user to fill in. Then, the user fills the form in and
  194. * submits it, triggering a second page request in which the form must be
  195. * built and processed. By default, $form and $form_state are built from
  196. * scratch during each of these page requests. Often, it is necessary or
  197. * desired to persist the $form and $form_state variables from the initial
  198. * page request to the one that processes the submission. 'cache' can be set
  199. * to TRUE to do this. A prominent example is an Ajax-enabled form, in which
  200. * ajax_process_form() enables form caching for all forms that include an
  201. * element with the #ajax property. (The Ajax handler has no way to build
  202. * the form itself, so must rely on the cached version.) Note that the
  203. * persistence of $form and $form_state happens automatically for
  204. * (multi-step) forms having the 'rebuild' flag set, regardless of the value
  205. * for 'cache'.
  206. * - no_cache: If set to TRUE the form will NOT be cached, even if 'cache' is
  207. * set.
  208. * - values: An associative array of values submitted to the form. The
  209. * validation functions and submit functions use this array for nearly all
  210. * their decision making. (Note that
  211. * @link http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#tree #tree @endlink
  212. * determines whether the values are a flat array or an array whose
  213. * structure parallels the $form array.)
  214. * - input: The array of values as they were submitted by the user. These are
  215. * raw and unvalidated, so should not be used without a thorough
  216. * understanding of security implications. In almost all cases, code should
  217. * use the data in the 'values' array exclusively. The most common use of
  218. * this key is for multi-step forms that need to clear some of the user
  219. * input when setting 'rebuild'. The values correspond to $_POST or $_GET,
  220. * depending on the 'method' chosen.
  221. * - always_process: If TRUE and the method is GET, a form_id is not
  222. * necessary. This should only be used on RESTful GET forms that do NOT
  223. * write data, as this could lead to security issues. It is useful so that
  224. * searches do not need to have a form_id in their query arguments to
  225. * trigger the search.
  226. * - must_validate: Ordinarily, a form is only validated once, but there are
  227. * times when a form is resubmitted internally and should be validated
  228. * again. Setting this to TRUE will force that to happen. This is most
  229. * likely to occur during Ajax operations.
  230. * - programmed: If TRUE, the form was submitted programmatically, usually
  231. * invoked via drupal_form_submit(). Defaults to FALSE.
  232. * - process_input: Boolean flag. TRUE signifies correct form submission.
  233. * This is always TRUE for programmed forms coming from drupal_form_submit()
  234. * (see 'programmed' key), or if the form_id coming from the $_POST data is
  235. * set and matches the current form_id.
  236. * - submitted: If TRUE, the form has been submitted. Defaults to FALSE.
  237. * - executed: If TRUE, the form was submitted and has been processed and
  238. * executed. Defaults to FALSE.
  239. * - triggering_element: (read-only) The form element that triggered
  240. * submission. This is the same as the deprecated
  241. * $form_state['clicked_button']. It is the element that caused submission,
  242. * which may or may not be a button (in the case of Ajax forms). This key is
  243. * often used to distinguish between various buttons in a submit handler,
  244. * and is also used in Ajax handlers.
  245. * - clicked_button: Deprecated. Use triggering_element instead.
  246. * - has_file_element: Internal. If TRUE, there is a file element and Form API
  247. * will set the appropriate 'enctype' HTML attribute on the form.
  248. * - groups: Internal. An array containing references to fieldsets to render
  249. * them within vertical tabs.
  250. * - storage: $form_state['storage'] is not a special key, and no specific
  251. * support is provided for it in the Form API. By tradition it was
  252. * the location where application-specific data was stored for communication
  253. * between the submit, validation, and form builder functions, especially
  254. * in a multi-step-style form. Form implementations may use any key(s)
  255. * within $form_state (other than the keys listed here and other reserved
  256. * ones used by Form API internals) for this kind of storage. The
  257. * recommended way to ensure that the chosen key doesn't conflict with ones
  258. * used by the Form API or other modules is to use the module name as the
  259. * key name or a prefix for the key name. For example, the Node module uses
  260. * $form_state['node'] in node editing forms to store information about the
  261. * node being edited, and this information stays available across successive
  262. * clicks of the "Preview" button as well as when the "Save" button is
  263. * finally clicked.
  264. * - buttons: A list containing copies of all submit and button elements in
  265. * the form.
  266. * - complete form: A reference to the $form variable containing the complete
  267. * form structure. #process, #after_build, #element_validate, and other
  268. * handlers being invoked on a form element may use this reference to access
  269. * other information in the form the element is contained in.
  270. * - temporary: An array holding temporary data accessible during the current
  271. * page request only. All $form_state properties that are not reserved keys
  272. * (see form_state_keys_no_cache()) persist throughout a multistep form
  273. * sequence. Form API provides this key for modules to communicate
  274. * information across form-related functions during a single page request.
  275. * It may be used to temporarily save data that does not need to or should
  276. * not be cached during the whole form workflow; e.g., data that needs to be
  277. * accessed during the current form build process only. There is no use-case
  278. * for this functionality in Drupal core.
  279. * - wrapper_callback: Modules that wish to pre-populate certain forms with
  280. * common elements, such as back/next/save buttons in multi-step form
  281. * wizards, may define a form builder function name that returns a form
  282. * structure, which is passed on to the actual form builder function.
  283. * Such implementations may either define the 'wrapper_callback' via
  284. * hook_forms() or have to invoke drupal_build_form() (instead of
  285. * drupal_get_form()) on their own in a custom menu callback to prepare
  286. * $form_state accordingly.
  287. * Information on how certain $form_state properties control redirection
  288. * behavior after form submission may be found in drupal_redirect_form().
  289. *
  290. * @return
  291. * The rendered form. This function may also perform a redirect and hence may
  292. * not return at all, depending upon the $form_state flags that were set.
  293. *
  294. * @see drupal_redirect_form()
  295. */
  296. function drupal_build_form($form_id, &$form_state) {
  297. // Ensure some defaults; if already set they will not be overridden.
  298. $form_state += form_state_defaults();
  299. if (!isset($form_state['input'])) {
  300. $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
  301. }
  302. if (isset($_SESSION['batch_form_state'])) {
  303. // We've been redirected here after a batch processing. The form has
  304. // already been processed, but needs to be rebuilt. See _batch_finished().
  305. $form_state = $_SESSION['batch_form_state'];
  306. unset($_SESSION['batch_form_state']);
  307. return drupal_rebuild_form($form_id, $form_state);
  308. }
  309. // If the incoming input contains a form_build_id, we'll check the cache for a
  310. // copy of the form in question. If it's there, we don't have to rebuild the
  311. // form to proceed. In addition, if there is stored form_state data from a
  312. // previous step, we'll retrieve it so it can be passed on to the form
  313. // processing code.
  314. $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  315. if ($check_cache) {
  316. $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  317. }
  318. // If the previous bit of code didn't result in a populated $form object, we
  319. // are hitting the form for the first time and we need to build it from
  320. // scratch.
  321. if (!isset($form)) {
  322. // If we attempted to serve the form from cache, uncacheable $form_state
  323. // keys need to be removed after retrieving and preparing the form, except
  324. // any that were already set prior to retrieving the form.
  325. if ($check_cache) {
  326. $form_state_before_retrieval = $form_state;
  327. }
  328. $form = drupal_retrieve_form($form_id, $form_state);
  329. drupal_prepare_form($form_id, $form, $form_state);
  330. // form_set_cache() removes uncacheable $form_state keys defined in
  331. // form_state_keys_no_cache() in order for multi-step forms to work
  332. // properly. This means that form processing logic for single-step forms
  333. // using $form_state['cache'] may depend on data stored in those keys
  334. // during drupal_retrieve_form()/drupal_prepare_form(), but form
  335. // processing should not depend on whether the form is cached or not, so
  336. // $form_state is adjusted to match what it would be after a
  337. // form_set_cache()/form_get_cache() sequence. These exceptions are
  338. // allowed to survive here:
  339. // - always_process: Does not make sense in conjunction with form caching
  340. // in the first place, since passing form_build_id as a GET parameter is
  341. // not desired.
  342. // - temporary: Any assigned data is expected to survives within the same
  343. // page request.
  344. if ($check_cache) {
  345. $uncacheable_keys = array_flip(array_diff(form_state_keys_no_cache(), array('always_process', 'temporary')));
  346. $form_state = array_diff_key($form_state, $uncacheable_keys);
  347. $form_state += $form_state_before_retrieval;
  348. }
  349. }
  350. // Now that we have a constructed form, process it. This is where:
  351. // - Element #process functions get called to further refine $form.
  352. // - User input, if any, gets incorporated in the #value property of the
  353. // corresponding elements and into $form_state['values'].
  354. // - Validation and submission handlers are called.
  355. // - If this submission is part of a multistep workflow, the form is rebuilt
  356. // to contain the information of the next step.
  357. // - If necessary, the form and form state are cached or re-cached, so that
  358. // appropriate information persists to the next page request.
  359. // All of the handlers in the pipeline receive $form_state by reference and
  360. // can use it to know or update information about the state of the form.
  361. drupal_process_form($form_id, $form, $form_state);
  362. // If this was a successful submission of a single-step form or the last step
  363. // of a multi-step form, then drupal_process_form() issued a redirect to
  364. // another page, or back to this page, but as a new request. Therefore, if
  365. // we're here, it means that this is either a form being viewed initially
  366. // before any user input, or there was a validation error requiring the form
  367. // to be re-displayed, or we're in a multi-step workflow and need to display
  368. // the form's next step. In any case, we have what we need in $form, and can
  369. // return it for rendering.
  370. return $form;
  371. }
  372. /**
  373. * Retrieves default values for the $form_state array.
  374. */
  375. function form_state_defaults() {
  376. return array(
  377. 'rebuild' => FALSE,
  378. 'rebuild_info' => array(),
  379. 'redirect' => NULL,
  380. // @todo 'args' is usually set, so no other default 'build_info' keys are
  381. // appended via += form_state_defaults().
  382. 'build_info' => array(
  383. 'args' => array(),
  384. 'files' => array(),
  385. ),
  386. 'temporary' => array(),
  387. 'submitted' => FALSE,
  388. 'executed' => FALSE,
  389. 'programmed' => FALSE,
  390. 'cache'=> FALSE,
  391. 'method' => 'post',
  392. 'groups' => array(),
  393. 'buttons' => array(),
  394. );
  395. }
  396. /**
  397. * Constructs a new $form from the information in $form_state.
  398. *
  399. * This is the key function for making multi-step forms advance from step to
  400. * step. It is called by drupal_process_form() when all user input processing,
  401. * including calling validation and submission handlers, for the request is
  402. * finished. If a validate or submit handler set $form_state['rebuild'] to TRUE,
  403. * and if other conditions don't preempt a rebuild from happening, then this
  404. * function is called to generate a new $form, the next step in the form
  405. * workflow, to be returned for rendering.
  406. *
  407. * Ajax form submissions are almost always multi-step workflows, so that is one
  408. * common use-case during which form rebuilding occurs. See ajax_form_callback()
  409. * for more information about creating Ajax-enabled forms.
  410. *
  411. * @param $form_id
  412. * The unique string identifying the desired form. If a function
  413. * with that name exists, it is called to build the form array.
  414. * Modules that need to generate the same form (or very similar forms)
  415. * using different $form_ids can implement hook_forms(), which maps
  416. * different $form_id values to the proper form constructor function. Examples
  417. * may be found in node_forms() and search_forms().
  418. * @param $form_state
  419. * A keyed array containing the current state of the form.
  420. * @param $old_form
  421. * (optional) A previously built $form. Used to retain the #build_id and
  422. * #action properties in Ajax callbacks and similar partial form rebuilds. The
  423. * only properties copied from $old_form are the ones which both exist in
  424. * $old_form and for which $form_state['rebuild_info']['copy'][PROPERTY] is
  425. * TRUE. If $old_form is not passed, the entire $form is rebuilt freshly.
  426. * 'rebuild_info' needs to be a separate top-level property next to
  427. * 'build_info', since the contained data must not be cached.
  428. *
  429. * @return
  430. * The newly built form.
  431. *
  432. * @see drupal_process_form()
  433. * @see ajax_form_callback()
  434. */
  435. function drupal_rebuild_form($form_id, &$form_state, $old_form = NULL) {
  436. $form = drupal_retrieve_form($form_id, $form_state);
  437. // If only parts of the form will be returned to the browser (e.g., Ajax or
  438. // RIA clients), re-use the old #build_id to not require client-side code to
  439. // manually update the hidden 'build_id' input element.
  440. // Otherwise, a new #build_id is generated, to not clobber the previous
  441. // build's data in the form cache; also allowing the user to go back to an
  442. // earlier build, make changes, and re-submit.
  443. // @see drupal_prepare_form()
  444. if (isset($old_form['#build_id']) && !empty($form_state['rebuild_info']['copy']['#build_id'])) {
  445. $form['#build_id'] = $old_form['#build_id'];
  446. }
  447. else {
  448. $form['#build_id'] = 'form-' . drupal_hash_base64(uniqid(mt_rand(), TRUE) . mt_rand());
  449. }
  450. // #action defaults to request_uri(), but in case of Ajax and other partial
  451. // rebuilds, the form is submitted to an alternate URL, and the original
  452. // #action needs to be retained.
  453. if (isset($old_form['#action']) && !empty($form_state['rebuild_info']['copy']['#action'])) {
  454. $form['#action'] = $old_form['#action'];
  455. }
  456. drupal_prepare_form($form_id, $form, $form_state);
  457. // Caching is normally done in drupal_process_form(), but what needs to be
  458. // cached is the $form structure before it passes through form_builder(),
  459. // so we need to do it here.
  460. // @todo For Drupal 8, find a way to avoid this code duplication.
  461. if (empty($form_state['no_cache'])) {
  462. form_set_cache($form['#build_id'], $form, $form_state);
  463. }
  464. // Clear out all group associations as these might be different when
  465. // re-rendering the form.
  466. $form_state['groups'] = array();
  467. // Return a fully built form that is ready for rendering.
  468. return form_builder($form_id, $form, $form_state);
  469. }
  470. /**
  471. * Fetches a form from cache.
  472. */
  473. function form_get_cache($form_build_id, &$form_state) {
  474. if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
  475. $form = $cached->data;
  476. global $user;
  477. if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
  478. if ($cached = cache_get('form_state_' . $form_build_id, 'cache_form')) {
  479. // Re-populate $form_state for subsequent rebuilds.
  480. $form_state = $cached->data + $form_state;
  481. // If the original form is contained in include files, load the files.
  482. // @see form_load_include()
  483. $form_state['build_info'] += array('files' => array());
  484. foreach ($form_state['build_info']['files'] as $file) {
  485. if (is_array($file)) {
  486. $file += array('type' => 'inc', 'name' => $file['module']);
  487. module_load_include($file['type'], $file['module'], $file['name']);
  488. }
  489. elseif (file_exists($file)) {
  490. require_once DRUPAL_ROOT . '/' . $file;
  491. }
  492. }
  493. }
  494. return $form;
  495. }
  496. }
  497. }
  498. /**
  499. * Stores a form in the cache.
  500. */
  501. function form_set_cache($form_build_id, $form, $form_state) {
  502. // 6 hours cache life time for forms should be plenty.
  503. $expire = 21600;
  504. // Cache form structure.
  505. if (isset($form)) {
  506. if ($GLOBALS['user']->uid) {
  507. $form['#cache_token'] = drupal_get_token();
  508. }
  509. cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
  510. }
  511. // Cache form state.
  512. if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
  513. cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
  514. }
  515. }
  516. /**
  517. * Returns an array of $form_state keys that shouldn't be cached.
  518. */
  519. function form_state_keys_no_cache() {
  520. return array(
  521. // Public properties defined by form constructors and form handlers.
  522. 'always_process',
  523. 'must_validate',
  524. 'rebuild',
  525. 'rebuild_info',
  526. 'redirect',
  527. 'no_redirect',
  528. 'temporary',
  529. // Internal properties defined by form processing.
  530. 'buttons',
  531. 'triggering_element',
  532. 'clicked_button',
  533. 'complete form',
  534. 'groups',
  535. 'input',
  536. 'method',
  537. 'submit_handlers',
  538. 'submitted',
  539. 'executed',
  540. 'validate_handlers',
  541. 'values',
  542. );
  543. }
  544. /**
  545. * Ensures an include file is loaded loaded whenever the form is processed.
  546. *
  547. * Example:
  548. * @code
  549. * // Load node.admin.inc from Node module.
  550. * form_load_include($form_state, 'inc', 'node', 'node.admin');
  551. * @endcode
  552. *
  553. * Use this function instead of module_load_include() from inside a form
  554. * constructor or any form processing logic as it ensures that the include file
  555. * is loaded whenever the form is processed. In contrast to using
  556. * module_load_include() directly, form_load_include() makes sure the include
  557. * file is correctly loaded also if the form is cached.
  558. *
  559. * @param $form_state
  560. * The current state of the form.
  561. * @param $type
  562. * The include file's type (file extension).
  563. * @param $module
  564. * The module to which the include file belongs.
  565. * @param $name
  566. * (optional) The base file name (without the $type extension). If omitted,
  567. * $module is used; i.e., resulting in "$module.$type" by default.
  568. *
  569. * @return
  570. * The filepath of the loaded include file, or FALSE if the include file was
  571. * not found or has been loaded already.
  572. *
  573. * @see module_load_include()
  574. */
  575. function form_load_include(&$form_state, $type, $module, $name = NULL) {
  576. if (!isset($name)) {
  577. $name = $module;
  578. }
  579. if (!isset($form_state['build_info']['files']["$module:$name.$type"])) {
  580. // Only add successfully included files to the form state.
  581. if ($result = module_load_include($type, $module, $name)) {
  582. $form_state['build_info']['files']["$module:$name.$type"] = array(
  583. 'type' => $type,
  584. 'module' => $module,
  585. 'name' => $name,
  586. );
  587. return $result;
  588. }
  589. }
  590. return FALSE;
  591. }
  592. /**
  593. * Retrieves, populates, and processes a form.
  594. *
  595. * This function allows you to supply values for form elements and submit a
  596. * form for processing. Compare to drupal_get_form(), which also builds and
  597. * processes a form, but does not allow you to supply values.
  598. *
  599. * There is no return value, but you can check to see if there are errors
  600. * by calling form_get_errors().
  601. *
  602. * @param $form_id
  603. * The unique string identifying the desired form. If a function
  604. * with that name exists, it is called to build the form array.
  605. * Modules that need to generate the same form (or very similar forms)
  606. * using different $form_ids can implement hook_forms(), which maps
  607. * different $form_id values to the proper form constructor function. Examples
  608. * may be found in node_forms() and search_forms().
  609. * @param $form_state
  610. * A keyed array containing the current state of the form. Most important is
  611. * the $form_state['values'] collection, a tree of data used to simulate the
  612. * incoming $_POST information from a user's form submission. If a key is not
  613. * filled in $form_state['values'], then the default value of the respective
  614. * element is used. To submit an unchecked checkbox or other control that
  615. * browsers submit by not having a $_POST entry, include the key, but set the
  616. * value to NULL.
  617. * @param ...
  618. * Any additional arguments are passed on to the functions called by
  619. * drupal_form_submit(), including the unique form constructor function.
  620. * For example, the node_edit form requires that a node object be passed
  621. * in here when it is called. Arguments that need to be passed by reference
  622. * should not be included here, but rather placed directly in the $form_state
  623. * build info array so that the reference can be preserved. For example, a
  624. * form builder function with the following signature:
  625. * @code
  626. * function mymodule_form($form, &$form_state, &$object) {
  627. * }
  628. * @endcode
  629. * would be called via drupal_form_submit() as follows:
  630. * @code
  631. * $form_state['values'] = $my_form_values;
  632. * $form_state['build_info']['args'] = array(&$object);
  633. * drupal_form_submit('mymodule_form', $form_state);
  634. * @endcode
  635. * For example:
  636. * @code
  637. * // register a new user
  638. * $form_state = array();
  639. * $form_state['values']['name'] = 'robo-user';
  640. * $form_state['values']['mail'] = 'robouser@example.com';
  641. * $form_state['values']['pass']['pass1'] = 'password';
  642. * $form_state['values']['pass']['pass2'] = 'password';
  643. * $form_state['values']['op'] = t('Create new account');
  644. * drupal_form_submit('user_register_form', $form_state);
  645. * @endcode
  646. */
  647. function drupal_form_submit($form_id, &$form_state) {
  648. if (!isset($form_state['build_info']['args'])) {
  649. $args = func_get_args();
  650. array_shift($args);
  651. array_shift($args);
  652. $form_state['build_info']['args'] = $args;
  653. }
  654. // Merge in default values.
  655. $form_state += form_state_defaults();
  656. // Populate $form_state['input'] with the submitted values before retrieving
  657. // the form, to be consistent with what drupal_build_form() does for
  658. // non-programmatic submissions (form builder functions may expect it to be
  659. // there).
  660. $form_state['input'] = $form_state['values'];
  661. $form_state['programmed'] = TRUE;
  662. $form = drupal_retrieve_form($form_id, $form_state);
  663. // Programmed forms are always submitted.
  664. $form_state['submitted'] = TRUE;
  665. // Reset form validation.
  666. $form_state['must_validate'] = TRUE;
  667. form_clear_error();
  668. drupal_prepare_form($form_id, $form, $form_state);
  669. drupal_process_form($form_id, $form, $form_state);
  670. }
  671. /**
  672. * Retrieves the structured array that defines a given form.
  673. *
  674. * @param $form_id
  675. * The unique string identifying the desired form. If a function
  676. * with that name exists, it is called to build the form array.
  677. * Modules that need to generate the same form (or very similar forms)
  678. * using different $form_ids can implement hook_forms(), which maps
  679. * different $form_id values to the proper form constructor function.
  680. * @param $form_state
  681. * A keyed array containing the current state of the form, including the
  682. * additional arguments to drupal_get_form() or drupal_form_submit() in the
  683. * 'args' component of the array.
  684. */
  685. function drupal_retrieve_form($form_id, &$form_state) {
  686. $forms = &drupal_static(__FUNCTION__);
  687. // Record the filepath of the include file containing the original form, so
  688. // the form builder callbacks can be loaded when the form is being rebuilt
  689. // from cache on a different path (such as 'system/ajax'). See
  690. // form_get_cache().
  691. // $menu_get_item() is not available at installation time.
  692. if (!isset($form_state['build_info']['files']['menu']) && !defined('MAINTENANCE_MODE')) {
  693. $item = menu_get_item();
  694. if (!empty($item['include_file'])) {
  695. // Do not use form_load_include() here, as the file is already loaded.
  696. // Anyway, form_get_cache() is able to handle filepaths too.
  697. $form_state['build_info']['files']['menu'] = $item['include_file'];
  698. }
  699. }
  700. // We save two copies of the incoming arguments: one for modules to use
  701. // when mapping form ids to constructor functions, and another to pass to
  702. // the constructor function itself.
  703. $args = $form_state['build_info']['args'];
  704. // We first check to see if there's a function named after the $form_id.
  705. // If there is, we simply pass the arguments on to it to get the form.
  706. if (!function_exists($form_id)) {
  707. // In cases where many form_ids need to share a central constructor function,
  708. // such as the node editing form, modules can implement hook_forms(). It
  709. // maps one or more form_ids to the correct constructor functions.
  710. //
  711. // We cache the results of that hook to save time, but that only works
  712. // for modules that know all their form_ids in advance. (A module that
  713. // adds a small 'rate this comment' form to each comment in a list
  714. // would need a unique form_id for each one, for example.)
  715. //
  716. // So, we call the hook if $forms isn't yet populated, OR if it doesn't
  717. // yet have an entry for the requested form_id.
  718. if (!isset($forms) || !isset($forms[$form_id])) {
  719. $forms = module_invoke_all('forms', $form_id, $args);
  720. }
  721. $form_definition = $forms[$form_id];
  722. if (isset($form_definition['callback arguments'])) {
  723. $args = array_merge($form_definition['callback arguments'], $args);
  724. }
  725. if (isset($form_definition['callback'])) {
  726. $callback = $form_definition['callback'];
  727. $form_state['build_info']['base_form_id'] = $callback;
  728. }
  729. // In case $form_state['wrapper_callback'] is not defined already, we also
  730. // allow hook_forms() to define one.
  731. if (!isset($form_state['wrapper_callback']) && isset($form_definition['wrapper_callback'])) {
  732. $form_state['wrapper_callback'] = $form_definition['wrapper_callback'];
  733. }
  734. }
  735. $form = array();
  736. // We need to pass $form_state by reference in order for forms to modify it,
  737. // since call_user_func_array() requires that referenced variables are passed
  738. // explicitly.
  739. $args = array_merge(array($form, &$form_state), $args);
  740. // When the passed $form_state (not using drupal_get_form()) defines a
  741. // 'wrapper_callback', then it requests to invoke a separate (wrapping) form
  742. // builder function to pre-populate the $form array with form elements, which
  743. // the actual form builder function ($callback) expects. This allows for
  744. // pre-populating a form with common elements for certain forms, such as
  745. // back/next/save buttons in multi-step form wizards. See drupal_build_form().
  746. if (isset($form_state['wrapper_callback']) && function_exists($form_state['wrapper_callback'])) {
  747. $form = call_user_func_array($form_state['wrapper_callback'], $args);
  748. // Put the prepopulated $form into $args.
  749. $args[0] = $form;
  750. }
  751. // If $callback was returned by a hook_forms() implementation, call it.
  752. // Otherwise, call the function named after the form id.
  753. $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
  754. $form['#form_id'] = $form_id;
  755. return $form;
  756. }
  757. /**
  758. * Processes a form submission.
  759. *
  760. * This function is the heart of form API. The form gets built, validated and in
  761. * appropriate cases, submitted and rebuilt.
  762. *
  763. * @param $form_id
  764. * The unique string identifying the current form.
  765. * @param $form
  766. * An associative array containing the structure of the form.
  767. * @param $form_state
  768. * A keyed array containing the current state of the form. This
  769. * includes the current persistent storage data for the form, and
  770. * any data passed along by earlier steps when displaying a
  771. * multi-step form. Additional information, like the sanitized $_POST
  772. * data, is also accumulated here.
  773. */
  774. function drupal_process_form($form_id, &$form, &$form_state) {
  775. $form_state['values'] = array();
  776. // With $_GET, these forms are always submitted if requested.
  777. if ($form_state['method'] == 'get' && !empty($form_state['always_process'])) {
  778. if (!isset($form_state['input']['form_build_id'])) {
  779. $form_state['input']['form_build_id'] = $form['#build_id'];
  780. }
  781. if (!isset($form_state['input']['form_id'])) {
  782. $form_state['input']['form_id'] = $form_id;
  783. }
  784. if (!isset($form_state['input']['form_token']) && isset($form['#token'])) {
  785. $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  786. }
  787. }
  788. // form_builder() finishes building the form by calling element #process
  789. // functions and mapping user input, if any, to #value properties, and also
  790. // storing the values in $form_state['values']. We need to retain the
  791. // unprocessed $form in case it needs to be cached.
  792. $unprocessed_form = $form;
  793. $form = form_builder($form_id, $form, $form_state);
  794. // Only process the input if we have a correct form submission.
  795. if ($form_state['process_input']) {
  796. drupal_validate_form($form_id, $form, $form_state);
  797. // drupal_html_id() maintains a cache of element IDs it has seen,
  798. // so it can prevent duplicates. We want to be sure we reset that
  799. // cache when a form is processed, so scenarios that result in
  800. // the form being built behind the scenes and again for the
  801. // browser don't increment all the element IDs needlessly.
  802. drupal_static_reset('drupal_html_id');
  803. if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
  804. // Execute form submit handlers.
  805. form_execute_handlers('submit', $form, $form_state);
  806. // We'll clear out the cached copies of the form and its stored data
  807. // here, as we've finished with them. The in-memory copies are still
  808. // here, though.
  809. if (!variable_get('cache', 0) && !empty($form_state['values']['form_build_id'])) {
  810. cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
  811. cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
  812. }
  813. // If batches were set in the submit handlers, we process them now,
  814. // possibly ending execution. We make sure we do not react to the batch
  815. // that is already being processed (if a batch operation performs a
  816. // drupal_form_submit).
  817. if ($batch =& batch_get() && !isset($batch['current_set'])) {
  818. // Store $form_state information in the batch definition.
  819. // We need the full $form_state when either:
  820. // - Some submit handlers were saved to be called during batch
  821. // processing. See form_execute_handlers().
  822. // - The form is multistep.
  823. // In other cases, we only need the information expected by
  824. // drupal_redirect_form().
  825. if ($batch['has_form_submits'] || !empty($form_state['rebuild'])) {
  826. $batch['form_state'] = $form_state;
  827. }
  828. else {
  829. $batch['form_state'] = array_intersect_key($form_state, array_flip(array('programmed', 'rebuild', 'storage', 'no_redirect', 'redirect')));
  830. }
  831. $batch['progressive'] = !$form_state['programmed'];
  832. batch_process();
  833. // Execution continues only for programmatic forms.
  834. // For 'regular' forms, we get redirected to the batch processing
  835. // page. Form redirection will be handled in _batch_finished(),
  836. // after the batch is processed.
  837. }
  838. // Set a flag to indicate the the form has been processed and executed.
  839. $form_state['executed'] = TRUE;
  840. // Redirect the form based on values in $form_state.
  841. drupal_redirect_form($form_state);
  842. }
  843. // Don't rebuild or cache form submissions invoked via drupal_form_submit().
  844. if (!empty($form_state['programmed'])) {
  845. return;
  846. }
  847. // If $form_state['rebuild'] has been set and input has been processed
  848. // without validation errors, we are in a multi-step workflow that is not
  849. // yet complete. A new $form needs to be constructed based on the changes
  850. // made to $form_state during this request. Normally, a submit handler sets
  851. // $form_state['rebuild'] if a fully executed form requires another step.
  852. // However, for forms that have not been fully executed (e.g., Ajax
  853. // submissions triggered by non-buttons), there is no submit handler to set
  854. // $form_state['rebuild']. It would not make sense to redisplay the
  855. // identical form without an error for the user to correct, so we also
  856. // rebuild error-free non-executed forms, regardless of
  857. // $form_state['rebuild'].
  858. // @todo D8: Simplify this logic; considering Ajax and non-HTML front-ends,
  859. // along with element-level #submit properties, it makes no sense to have
  860. // divergent form execution based on whether the triggering element has
  861. // #executes_submit_callback set to TRUE.
  862. if (($form_state['rebuild'] || !$form_state['executed']) && !form_get_errors()) {
  863. // Form building functions (e.g., _form_builder_handle_input_element())
  864. // may use $form_state['rebuild'] to determine if they are running in the
  865. // context of a rebuild, so ensure it is set.
  866. $form_state['rebuild'] = TRUE;
  867. $form = drupal_rebuild_form($form_id, $form_state, $form);
  868. }
  869. }
  870. // After processing the form, the form builder or a #process callback may
  871. // have set $form_state['cache'] to indicate that the form and form state
  872. // shall be cached. But the form may only be cached if the 'no_cache' property
  873. // is not set to TRUE. Only cache $form as it was prior to form_builder(),
  874. // because form_builder() must run for each request to accommodate new user
  875. // input. Rebuilt forms are not cached here, because drupal_rebuild_form()
  876. // already takes care of that.
  877. if (!$form_state['rebuild'] && $form_state['cache'] && empty($form_state['no_cache'])) {
  878. form_set_cache($form['#build_id'], $unprocessed_form, $form_state);
  879. }
  880. }
  881. /**
  882. * Prepares a structured form array.
  883. *
  884. * Adds required elements, executes any hook_form_alter functions, and
  885. * optionally inserts a validation token to prevent tampering.
  886. *
  887. * @param $form_id
  888. * A unique string identifying the form for validation, submission,
  889. * theming, and hook_form_alter functions.
  890. * @param $form
  891. * An associative array containing the structure of the form.
  892. * @param $form_state
  893. * A keyed array containing the current state of the form. Passed
  894. * in here so that hook_form_alter() calls can use it, as well.
  895. */
  896. function drupal_prepare_form($form_id, &$form, &$form_state) {
  897. global $user;
  898. $form['#type'] = 'form';
  899. $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
  900. // Fix the form method, if it is 'get' in $form_state, but not in $form.
  901. if ($form_state['method'] == 'get' && !isset($form['#method'])) {
  902. $form['#method'] = 'get';
  903. }
  904. // Generate a new #build_id for this form, if none has been set already. The
  905. // form_build_id is used as key to cache a particular build of the form. For
  906. // multi-step forms, this allows the user to go back to an earlier build, make
  907. // changes, and re-submit.
  908. // @see drupal_build_form()
  909. // @see drupal_rebuild_form()
  910. if (!isset($form['#build_id'])) {
  911. $form['#build_id'] = 'form-' . drupal_hash_base64(uniqid(mt_rand(), TRUE) . mt_rand());
  912. }
  913. $form['form_build_id'] = array(
  914. '#type' => 'hidden',
  915. '#value' => $form['#build_id'],
  916. '#id' => $form['#build_id'],
  917. '#name' => 'form_build_id',
  918. );
  919. // Add a token, based on either #token or form_id, to any form displayed to
  920. // authenticated users. This ensures that any submitted form was actually
  921. // requested previously by the user and protects against cross site request
  922. // forgeries.
  923. // This does not apply to programmatically submitted forms. Furthermore, since
  924. // tokens are session-bound and forms displayed to anonymous users are very
  925. // likely cached, we cannot assign a token for them.
  926. // During installation, there is no $user yet.
  927. if (!empty($user->uid) && !$form_state['programmed']) {
  928. // Form constructors may explicitly set #token to FALSE when cross site
  929. // request forgery is irrelevant to the form, such as search forms.
  930. if (isset($form['#token']) && $form['#token'] === FALSE) {
  931. unset($form['#token']);
  932. }
  933. // Otherwise, generate a public token based on the form id.
  934. else {
  935. $form['#token'] = $form_id;
  936. $form['form_token'] = array(
  937. '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
  938. '#type' => 'token',
  939. '#default_value' => drupal_get_token($form['#token']),
  940. );
  941. }
  942. }
  943. if (isset($form_id)) {
  944. $form['form_id'] = array(
  945. '#type' => 'hidden',
  946. '#value' => $form_id,
  947. '#id' => drupal_html_id("edit-$form_id"),
  948. );
  949. }
  950. if (!isset($form['#id'])) {
  951. $form['#id'] = drupal_html_id($form_id);
  952. }
  953. $form += element_info('form');
  954. $form += array('#tree' => FALSE, '#parents' => array());
  955. if (!isset($form['#validate'])) {
  956. // Ensure that modules can rely on #validate being set.
  957. $form['#validate'] = array();
  958. // Check for a handler specific to $form_id.
  959. if (function_exists($form_id . '_validate')) {
  960. $form['#validate'][] = $form_id . '_validate';
  961. }
  962. // Otherwise check whether this is a shared form and whether there is a
  963. // handler for the shared $form_id.
  964. elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_validate')) {
  965. $form['#validate'][] = $form_state['build_info']['base_form_id'] . '_validate';
  966. }
  967. }
  968. if (!isset($form['#submit'])) {
  969. // Ensure that modules can rely on #submit being set.
  970. $form['#submit'] = array();
  971. // Check for a handler specific to $form_id.
  972. if (function_exists($form_id . '_submit')) {
  973. $form['#submit'][] = $form_id . '_submit';
  974. }
  975. // Otherwise check whether this is a shared form and whether there is a
  976. // handler for the shared $form_id.
  977. elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
  978. $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
  979. }
  980. }
  981. // If no #theme has been set, automatically apply theme suggestions.
  982. // theme_form() itself is in #theme_wrappers and not #theme. Therefore, the
  983. // #theme function only has to care for rendering the inner form elements,
  984. // not the form itself.
  985. if (!isset($form['#theme'])) {
  986. $form['#theme'] = array($form_id);
  987. if (isset($form_state['build_info']['base_form_id'])) {
  988. $form['#theme'][] = $form_state['build_info']['base_form_id'];
  989. }
  990. }
  991. // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
  992. // hook_form_FORM_ID_alter() implementations.
  993. $hooks = array('form');
  994. if (isset($form_state['build_info']['base_form_id'])) {
  995. $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
  996. }
  997. $hooks[] = 'form_' . $form_id;
  998. drupal_alter($hooks, $form, $form_state, $form_id);
  999. }
  1000. /**
  1001. * Validates user-submitted form data in the $form_state array.
  1002. *
  1003. * @param $form_id
  1004. * A unique string identifying the form for validation, submission,
  1005. * theming, and hook_form_alter functions.
  1006. * @param $form
  1007. * An associative array containing the structure of the form, which is passed
  1008. * by reference. Form validation handlers are able to alter the form structure
  1009. * (like #process and #after_build callbacks during form building) in case of
  1010. * a validation error. If a validation handler alters the form structure, it
  1011. * is responsible for validating the values of changed form elements in
  1012. * $form_state['values'] to prevent form submit handlers from receiving
  1013. * unvalidated values.
  1014. * @param $form_state
  1015. * A keyed array containing the current state of the form. The current
  1016. * user-submitted data is stored in $form_state['values'], though
  1017. * form validation functions are passed an explicit copy of the
  1018. * values for the sake of simplicity. Validation handlers can also
  1019. * $form_state to pass information on to submit handlers. For example:
  1020. * $form_state['data_for_submission'] = $data;
  1021. * This technique is useful when validation requires file parsing,
  1022. * web service requests, or other expensive requests that should
  1023. * not be repeated in the submission step.
  1024. */
  1025. function drupal_validate_form($form_id, &$form, &$form_state) {
  1026. $validated_forms = &drupal_static(__FUNCTION__, array());
  1027. if (isset($validated_forms[$form_id]) && empty($form_state['must_validate'])) {
  1028. return;
  1029. }
  1030. // If the session token was set by drupal_prepare_form(), ensure that it
  1031. // matches the current user's session.
  1032. if (isset($form['#token'])) {
  1033. if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
  1034. $path = current_path();
  1035. $query = drupal_get_query_parameters();
  1036. $url = url($path, array('query' => $query));
  1037. // Setting this error will cause the form to fail validation.
  1038. form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
  1039. }
  1040. }
  1041. _form_validate($form, $form_state, $form_id);
  1042. $validated_forms[$form_id] = TRUE;
  1043. // If validation errors are limited then remove any non validated form values,
  1044. // so that only values that passed validation are left for submit callbacks.
  1045. if (isset($form_state['triggering_element']['#limit_validation_errors']) && $form_state['triggering_element']['#limit_validation_errors'] !== FALSE) {
  1046. $values = array();
  1047. foreach ($form_state['triggering_element']['#limit_validation_errors'] as $section) {
  1048. // If the section exists within $form_state['values'], even if the value
  1049. // is NULL, copy it to $values.
  1050. $section_exists = NULL;
  1051. $value = drupal_array_get_nested_value($form_state['values'], $section, $section_exists);
  1052. if ($section_exists) {
  1053. drupal_array_set_nested_value($values, $section, $value);
  1054. }
  1055. }
  1056. // A button's #value does not require validation, so for convenience we
  1057. // allow the value of the clicked button to be retained in its normal
  1058. // $form_state['values'] locations, even if these locations are not included
  1059. // in #limit_validation_errors.
  1060. if (isset($form_state['triggering_element']['#button_type'])) {
  1061. $button_value = $form_state['triggering_element']['#value'];
  1062. // Like all input controls, the button value may be in the location
  1063. // dictated by #parents. If it is, copy it to $values, but do not override
  1064. // what may already be in $values.
  1065. $parents = $form_state['triggering_element']['#parents'];
  1066. if (!drupal_array_nested_key_exists($values, $parents) && drupal_array_get_nested_value($form_state['values'], $parents) === $button_value) {
  1067. drupal_array_set_nested_value($values, $parents, $button_value);
  1068. }
  1069. // Additionally, form_builder() places the button value in
  1070. // $form_state['values'][BUTTON_NAME]. If it's still there, after
  1071. // validation handlers have run, copy it to $values, but do not override
  1072. // what may already be in $values.
  1073. $name = $form_state['triggering_element']['#name'];
  1074. if (!isset($values[$name]) && isset($form_state['values'][$name]) && $form_state['values'][$name] === $button_value) {
  1075. $values[$name] = $button_value;
  1076. }
  1077. }
  1078. $form_state['values'] = $values;
  1079. }
  1080. }
  1081. /**
  1082. * Redirects the user to a URL after a form has been processed.
  1083. *
  1084. * After a form was executed, the data in $form_state controls whether the form
  1085. * is redirected. By default, we redirect to a new destination page. The path
  1086. * of the destination page can be set in $form_state['redirect'], as either a
  1087. * string containing the destination or an array of arguments compatible with
  1088. * drupal_goto(). If that is not set, the user is redirected to the current
  1089. * page to display a fresh, unpopulated copy of the form.
  1090. *
  1091. * For example, to redirect to 'node':
  1092. * @code
  1093. * $form_state['redirect'] = 'node';
  1094. * @endcode
  1095. * Or to redirect to 'node/123?foo=bar#baz':
  1096. * @code
  1097. * $form_state['redirect'] = array(
  1098. * 'node/123',
  1099. * array(
  1100. * 'query' => array(
  1101. * 'foo' => 'bar',
  1102. * ),
  1103. * 'fragment' => 'baz',
  1104. * ),
  1105. * );
  1106. * @endcode
  1107. *
  1108. * There are several triggers that may prevent a redirection though:
  1109. * - If $form_state['redirect'] is FALSE, a form builder function or form
  1110. * validation/submit handler does not want a user to be redirected, which
  1111. * means that drupal_goto() is not invoked. For most forms, the redirection
  1112. * logic will be the same regardless of whether $form_state['redirect'] is
  1113. * undefined or FALSE. However, in case it was not defined and the current
  1114. * request contains a 'destination' query string, drupal_goto() will redirect
  1115. * to that given destination instead. Only setting $form_state['redirect'] to
  1116. * FALSE will prevent any redirection.
  1117. * - If $form_state['no_redirect'] is TRUE, then the callback that originally
  1118. * built the form explicitly disallows any redirection, regardless of the
  1119. * redirection value in $form_state['redirect']. For example, ajax_get_form()
  1120. * defines $form_state['no_redirect'] when building a form in an Ajax
  1121. * callback to prevent any redirection. $form_state['no_redirect'] should NOT
  1122. * be altered by form builder functions or form validation/submit handlers.
  1123. * - If $form_state['programmed'] is TRUE, the form submission was usually
  1124. * invoked via drupal_form_submit(), so any redirection would break the script
  1125. * that invoked drupal_form_submit().
  1126. * - If $form_state['rebuild'] is TRUE, the form needs to be rebuilt without
  1127. * redirection.
  1128. *
  1129. * @param $form_state
  1130. * A keyed array containing the current state of the form.
  1131. *
  1132. * @see drupal_process_form()
  1133. * @see drupal_build_form()
  1134. */
  1135. function drupal_redirect_form($form_state) {
  1136. // Skip redirection for form submissions invoked via drupal_form_submit().
  1137. if (!empty($form_state['programmed'])) {
  1138. return;
  1139. }
  1140. // Skip redirection if rebuild is activated.
  1141. if (!empty($form_state['rebuild'])) {
  1142. return;
  1143. }
  1144. // Skip redirection if it was explicitly disallowed.
  1145. if (!empty($form_state['no_redirect'])) {
  1146. return;
  1147. }
  1148. // Only invoke drupal_goto() if redirect value was not set to FALSE.
  1149. if (!isset($form_state['redirect']) || $form_state['redirect'] !== FALSE) {
  1150. if (isset($form_state['redirect'])) {
  1151. if (is_array($form_state['redirect'])) {
  1152. call_user_func_array('drupal_goto', $form_state['redirect']);
  1153. }
  1154. else {
  1155. // This function can be called from the installer, which guarantees
  1156. // that $redirect will always be a string, so catch that case here
  1157. // and use the appropriate redirect function.
  1158. $function = drupal_installation_attempted() ? 'install_goto' : 'drupal_goto';
  1159. $function($form_state['redirect']);
  1160. }
  1161. }
  1162. drupal_goto($_GET['q']);
  1163. }
  1164. }
  1165. /**
  1166. * Performs validation on form elements.
  1167. *
  1168. * First ensures required fields are completed, #maxlength is not exceeded, and
  1169. * selected options were in the list of options given to the user. Then calls
  1170. * user-defined validators.
  1171. *
  1172. * @param $elements
  1173. * An associative array containing the structure of the form.
  1174. * @param $form_state
  1175. * A keyed array containing the current state of the form. The current
  1176. * user-submitted data is stored in $form_state['values'], though
  1177. * form validation functions are passed an explicit copy of the
  1178. * values for the sake of simplicity. Validation handlers can also
  1179. * $form_state to pass information on to submit handlers. For example:
  1180. * $form_state['data_for_submission'] = $data;
  1181. * This technique is useful when validation requires file parsing,
  1182. * web service requests, or other expensive requests that should
  1183. * not be repeated in the submission step.
  1184. * @param $form_id
  1185. * A unique string identifying the form for validation, submission,
  1186. * theming, and hook_form_alter functions.
  1187. */
  1188. function _form_validate(&$elements, &$form_state, $form_id = NULL) {
  1189. // Also used in the installer, pre-database setup.
  1190. $t = get_t();
  1191. // Recurse through all children.
  1192. foreach (element_children($elements) as $key) {
  1193. if (isset($elements[$key]) && $elements[$key]) {
  1194. _form_validate($elements[$key], $form_state);
  1195. }
  1196. }
  1197. // Validate the current input.
  1198. if (!isset($elements['#validated']) || !$elements['#validated']) {
  1199. // The following errors are always shown.
  1200. if (isset($elements['#needs_validation'])) {
  1201. // Verify that the value is not longer than #maxlength.
  1202. if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
  1203. form_error($elements, $t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
  1204. }
  1205. if (isset($elements['#options']) && isset($elements['#value'])) {
  1206. if ($elements['#type'] == 'select') {
  1207. $options = form_options_flatten($elements['#options']);
  1208. }
  1209. else {
  1210. $options = $elements['#options'];
  1211. }
  1212. if (is_array($elements['#value'])) {
  1213. $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
  1214. foreach ($value as $v) {
  1215. if (!isset($options[$v])) {
  1216. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  1217. watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  1218. }
  1219. }
  1220. }
  1221. // Non-multiple select fields always have a value in HTML. If the user
  1222. // does not change the form, it will be the value of the first option.
  1223. // Because of this, form validation for the field will almost always
  1224. // pass, even if the user did not select anything. To work around this
  1225. // browser behavior, required select fields without a #default_value get
  1226. // an additional, first empty option. In case the submitted value is
  1227. // identical to the empty option's value, we reset the element's value
  1228. // to NULL to trigger the regular #required handling below.
  1229. // @see form_process_select()
  1230. elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
  1231. $elements['#value'] = NULL;
  1232. form_set_value($elements, NULL, $form_state);
  1233. }
  1234. elseif (!isset($options[$elements['#value']])) {
  1235. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  1236. watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  1237. }
  1238. }
  1239. }
  1240. // While this element is being validated, it may be desired that some calls
  1241. // to form_set_error() be suppressed and not result in a form error, so
  1242. // that a button that implements low-risk functionality (such as "Previous"
  1243. // or "Add more") that doesn't require all user input to be valid can still
  1244. // have its submit handlers triggered. The triggering element's
  1245. // #limit_validation_errors property contains the information for which
  1246. // errors are needed, and all other errors are to be suppressed. The
  1247. // #limit_validation_errors property is ignored if submit handlers will run,
  1248. // but the element doesn't have a #submit property, because it's too large a
  1249. // security risk to have any invalid user input when executing form-level
  1250. // submit handlers.
  1251. if (isset($form_state['triggering_element']['#limit_validation_errors']) && ($form_state['triggering_element']['#limit_validation_errors'] !== FALSE) && !($form_state['submitted'] && !isset($form_state['triggering_element']['#submit']))) {
  1252. form_set_error(NULL, '', $form_state['triggering_element']['#limit_validation_errors']);
  1253. }
  1254. // If submit handlers won't run (due to the submission having been triggered
  1255. // by an element whose #executes_submit_callback property isn't TRUE), then
  1256. // it's safe to suppress all validation errors, and we do so by default,
  1257. // which is particularly useful during an Ajax submission triggered by a
  1258. // non-button. An element can override this default by setting the
  1259. // #limit_validation_errors property. For button element types,
  1260. // #limit_validation_errors defaults to FALSE (via system_element_info()),
  1261. // so that full validation is their default behavior.
  1262. elseif (isset($form_state['triggering_element']) && !isset($form_state['triggering_element']['#limit_validation_errors']) && !$form_state['submitted']) {
  1263. form_set_error(NULL, '', array());
  1264. }
  1265. // As an extra security measure, explicitly turn off error suppression if
  1266. // one of the above conditions wasn't met. Since this is also done at the
  1267. // end of this function, doing it here is only to handle the rare edge case
  1268. // where a validate handler invokes form processing of another form.
  1269. else {
  1270. drupal_static_reset('form_set_error:limit_validation_errors');
  1271. }
  1272. // Make sure a value is passed when the field is required.
  1273. if (isset($elements['#needs_validation']) && $elements['#required']) {
  1274. // A simple call to empty() will not cut it here as some fields, like
  1275. // checkboxes, can return a valid value of '0'. Instead, check the
  1276. // length if it's a string, and the item count if it's an array.
  1277. // An unchecked checkbox has a #value of integer 0, different than string
  1278. // '0', which could be a valid value.
  1279. $is_empty_multiple = (!count($elements['#value']));
  1280. $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
  1281. $is_empty_value = ($elements['#value'] === 0);
  1282. if ($is_empty_multiple || $is_empty_string || $is_empty_value) {
  1283. // Although discouraged, a #title is not mandatory for form elements. In
  1284. // case there is no #title, we cannot set a form error message.
  1285. // Instead of setting no #title, form constructors are encouraged to set
  1286. // #title_display to 'invisible' to improve accessibility.
  1287. if (isset($elements['#title'])) {
  1288. form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
  1289. }
  1290. else {
  1291. form_error($elements);
  1292. }
  1293. }
  1294. }
  1295. // Call user-defined form level validators.
  1296. if (isset($form_id)) {
  1297. form_execute_handlers('validate', $elements, $form_state);
  1298. }
  1299. // Call any element-specific validators. These must act on the element
  1300. // #value data.
  1301. elseif (isset($elements['#element_validate'])) {
  1302. foreach ($elements['#element_validate'] as $function) {
  1303. $function($elements, $form_state, $form_state['complete form']);
  1304. }
  1305. }
  1306. $elements['#validated'] = TRUE;
  1307. }
  1308. // Done validating this element, so turn off error suppression.
  1309. // _form_validate() turns it on again when starting on the next element, if
  1310. // it's still appropriate to do so.
  1311. drupal_static_reset('form_set_error:limit_validation_errors');
  1312. }
  1313. /**
  1314. * Executes custom validation and submission handlers for a given form.
  1315. *
  1316. * Button-specific handlers are checked first. If none exist, the function
  1317. * falls back to form-level handlers.
  1318. *
  1319. * @param $type
  1320. * The type of handler to execute. 'validate' or 'submit' are the
  1321. * defaults used by Form API.
  1322. * @param $form
  1323. * An associative array containing the structure of the form.
  1324. * @param $form_state
  1325. * A keyed array containing the current state of the form. If the user
  1326. * submitted the form by clicking a button with custom handler functions
  1327. * defined, those handlers will be stored here.
  1328. */
  1329. function form_execute_handlers($type, &$form, &$form_state) {
  1330. $return = FALSE;
  1331. // If there was a button pressed, use its handlers.
  1332. if (isset($form_state[$type . '_handlers'])) {
  1333. $handlers = $form_state[$type . '_handlers'];
  1334. }
  1335. // Otherwise, check for a form-level handler.
  1336. elseif (isset($form['#' . $type])) {
  1337. $handlers = $form['#' . $type];
  1338. }
  1339. else {
  1340. $handlers = array();
  1341. }
  1342. foreach ($handlers as $function) {
  1343. // Check if a previous _submit handler has set a batch, but make sure we
  1344. // do not react to a batch that is already being processed (for instance
  1345. // if a batch operation performs a drupal_form_submit()).
  1346. if ($type == 'submit' && ($batch =& batch_get()) && !isset($batch['id'])) {
  1347. // Some previous submit handler has set a batch. To ensure correct
  1348. // execution order, store the call in a special 'control' batch set.
  1349. // See _batch_next_set().
  1350. $batch['sets'][] = array('form_submit' => $function);
  1351. $batch['has_form_submits'] = TRUE;
  1352. }
  1353. else {
  1354. $function($form, $form_state);
  1355. }
  1356. $return = TRUE;
  1357. }
  1358. return $return;
  1359. }
  1360. /**
  1361. * Files an error against a form element.
  1362. *
  1363. * When a validation error is detected, the validator calls form_set_error() to
  1364. * indicate which element needs to be changed and provide an error message. This
  1365. * causes the Form API to not execute the form submit handlers, and instead to
  1366. * re-display the form to the user with the corresponding elements rendered with
  1367. * an 'error' CSS class (shown as red by default).
  1368. *
  1369. * The standard form_set_error() behavior can be changed if a button provides
  1370. * the #limit_validation_errors property. Multistep forms not wanting to
  1371. * validate the whole form can set #limit_validation_errors on buttons to
  1372. * limit validation errors to only certain elements. For example, pressing the
  1373. * "Previous" button in a multistep form should not fire validation errors just
  1374. * because the current step has invalid values. If #limit_validation_errors is
  1375. * set on a clicked button, the button must also define a #submit property
  1376. * (may be set to an empty array). Any #submit handlers will be executed even if
  1377. * there is invalid input, so extreme care should be taken with respect to any
  1378. * actions taken by them. This is typically not a problem with buttons like
  1379. * "Previous" or "Add more" that do not invoke persistent storage of the
  1380. * submitted form values. Do not use the #limit_validation_errors property on
  1381. * buttons that trigger saving of form values to the database.
  1382. *
  1383. * The #limit_validation_errors property is a list of "sections" within
  1384. * $form_state['values'] that must contain valid values. Each "section" is an
  1385. * array with the ordered set of keys needed to reach that part of
  1386. * $form_state['values'] (i.e., the #parents property of the element).
  1387. *
  1388. * Example 1: Allow the "Previous" button to function, regardless of whether any
  1389. * user input is valid.
  1390. *
  1391. * @code
  1392. * $form['actions']['previous'] = array(
  1393. * '#type' => 'submit',
  1394. * '#value' => t('Previous'),
  1395. * '#limit_validation_errors' => array(), // No validation.
  1396. * '#submit' => array('some_submit_function'), // #submit required.
  1397. * );
  1398. * @endcode
  1399. *
  1400. * Example 2: Require some, but not all, user input to be valid to process the
  1401. * submission of a "Previous" button.
  1402. *
  1403. * @code
  1404. * $form['actions']['previous'] = array(
  1405. * '#type' => 'submit',
  1406. * '#value' => t('Previous'),
  1407. * '#limit_validation_errors' => array(
  1408. * array('step1'), // Validate $form_state['values']['step1'].
  1409. * array('foo', 'bar'), // Validate $form_state['values']['foo']['bar'].
  1410. * ),
  1411. * '#submit' => array('some_submit_function'), // #submit required.
  1412. * );
  1413. * @endcode
  1414. *
  1415. * This will require $form_state['values']['step1'] and everything within it
  1416. * (for example, $form_state['values']['step1']['choice']) to be valid, so
  1417. * calls to form_set_error('step1', $message) or
  1418. * form_set_error('step1][choice', $message) will prevent the submit handlers
  1419. * from running, and result in the error message being displayed to the user.
  1420. * However, calls to form_set_error('step2', $message) and
  1421. * form_set_error('step2][groupX][choiceY', $message) will be suppressed,
  1422. * resulting in the message not being displayed to the user, and the submit
  1423. * handlers will run despite $form_state['values']['step2'] and
  1424. * $form_state['values']['step2']['groupX']['choiceY'] containing invalid
  1425. * values. Errors for an invalid $form_state['values']['foo'] will be
  1426. * suppressed, but errors flagging invalid values for
  1427. * $form_state['values']['foo']['bar'] and everything within it will be
  1428. * flagged and submission prevented.
  1429. *
  1430. * Partial form validation is implemented by suppressing errors rather than by
  1431. * skipping the input processing and validation steps entirely, because some
  1432. * forms have button-level submit handlers that call Drupal API functions that
  1433. * assume that certain data exists within $form_state['values'], and while not
  1434. * doing anything with that data that requires it to be valid, PHP errors
  1435. * would be triggered if the input processing and validation steps were fully
  1436. * skipped.
  1437. *
  1438. * @param $name
  1439. * The name of the form element. If the #parents property of your form
  1440. * element is array('foo', 'bar', 'baz') then you may set an error on 'foo'
  1441. * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every
  1442. * element where the #parents array starts with 'foo'.
  1443. * @param $message
  1444. * The error message to present to the user.
  1445. * @param $limit_validation_errors
  1446. * Internal use only. The #limit_validation_errors property of the clicked
  1447. * button, if it exists.
  1448. *
  1449. * @return
  1450. * Return value is for internal use only. To get a list of errors, use
  1451. * form_get_errors() or form_get_error().
  1452. *
  1453. * @see http://drupal.org/node/370537
  1454. * @see http://drupal.org/node/763376
  1455. */
  1456. function form_set_error($name = NULL, $message = '', $limit_validation_errors = NULL) {
  1457. $form = &drupal_static(__FUNCTION__, array());
  1458. $sections = &drupal_static(__FUNCTION__ . ':limit_validation_errors');
  1459. if (isset($limit_validation_errors)) {
  1460. $sections = $limit_validation_errors;
  1461. }
  1462. if (isset($name) && !isset($form[$name])) {
  1463. $record = TRUE;
  1464. if (isset($sections)) {
  1465. // #limit_validation_errors is an array of "sections" within which user
  1466. // input must be valid. If the element is within one of these sections,
  1467. // the error must be recorded. Otherwise, it can be suppressed.
  1468. // #limit_validation_errors can be an empty array, in which case all
  1469. // errors are suppressed. For example, a "Previous" button might want its
  1470. // submit action to be triggered even if none of the submitted values are
  1471. // valid.
  1472. $record = FALSE;
  1473. foreach ($sections as $section) {
  1474. // Exploding by '][' reconstructs the element's #parents. If the
  1475. // reconstructed #parents begin with the same keys as the specified
  1476. // section, then the element's values are within the part of
  1477. // $form_state['values'] that the clicked button requires to be valid,
  1478. // so errors for this element must be recorded. As the exploded array
  1479. // will all be strings, we need to cast every value of the section
  1480. // array to string.
  1481. if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
  1482. $record = TRUE;
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. if ($record) {
  1488. $form[$name] = $message;
  1489. if ($message) {
  1490. drupal_set_message($message, 'error');
  1491. }
  1492. }
  1493. }
  1494. return $form;
  1495. }
  1496. /**
  1497. * Clears all errors against all form elements made by form_set_error().
  1498. */
  1499. function form_clear_error() {
  1500. drupal_static_reset('form_set_error');
  1501. }
  1502. /**
  1503. * Returns an associative array of all errors.
  1504. */
  1505. function form_get_errors() {
  1506. $form = form_set_error();
  1507. if (!empty($form)) {
  1508. return $form;
  1509. }
  1510. }
  1511. /**
  1512. * Returns the error message filed against the given form element.
  1513. *
  1514. * Form errors higher up in the form structure override deeper errors as well as
  1515. * errors on the element itself.
  1516. */
  1517. function form_get_error($element) {
  1518. $form = form_set_error();
  1519. $parents = array();
  1520. foreach ($element['#parents'] as $parent) {
  1521. $parents[] = $parent;
  1522. $key = implode('][', $parents);
  1523. if (isset($form[$key])) {
  1524. return $form[$key];
  1525. }
  1526. }
  1527. }
  1528. /**
  1529. * Flags an element as having an error.
  1530. */
  1531. function form_error(&$element, $message = '') {
  1532. form_set_error(implode('][', $element['#parents']), $message);
  1533. }
  1534. /**
  1535. * Builds and processes all elements in the structured form array.
  1536. *
  1537. * Adds any required properties to each element, maps the incoming input data
  1538. * to the proper elements, and executes any #process handlers attached to a
  1539. * specific element.
  1540. *
  1541. * This is one of the three primary functions that recursively iterates a form
  1542. * array. This one does it for completing the form building process. The other
  1543. * two are _form_validate() (invoked via drupal_validate_form() and used to
  1544. * invoke validation logic for each element) and drupal_render() (for rendering
  1545. * each element). Each of these three pipelines provides ample opportunity for
  1546. * modules to customize what happens. For example, during this function's life
  1547. * cycle, the following functions get called for each element:
  1548. * - $element['#value_callback']: A function that implements how user input is
  1549. * mapped to an element's #value property. This defaults to a function named
  1550. * 'form_type_TYPE_value' where TYPE is $element['#type'].
  1551. * - $element['#process']: An array of functions called after user input has
  1552. * been mapped to the element's #value property. These functions can be used
  1553. * to dynamically add child elements: for example, for the 'date' element
  1554. * type, one of the functions in this array is form_process_date(), which adds
  1555. * the individual 'year', 'month', 'day', etc. child elements. These functions
  1556. * can also be used to set additional properties or implement special logic
  1557. * other than adding child elements: for example, for the 'fieldset' element
  1558. * type, one of the functions in this array is form_process_fieldset(), which
  1559. * adds the attributes and JavaScript needed to make the fieldset collapsible
  1560. * if the #collapsible property is set. The #process functions are called in
  1561. * preorder traversal, meaning they are called for the parent element first,
  1562. * then for the child elements.
  1563. * - $element['#after_build']: An array of functions called after form_builder()
  1564. * is done with its processing of the element. These are called in postorder
  1565. * traversal, meaning they are called for the child elements first, then for
  1566. * the parent element.
  1567. * There are similar properties containing callback functions invoked by
  1568. * _form_validate() and drupal_render(), appropriate for those operations.
  1569. *
  1570. * Developers are strongly encouraged to integrate the functionality needed by
  1571. * their form or module within one of these three pipelines, using the
  1572. * appropriate callback property, rather than implementing their own recursive
  1573. * traversal of a form array. This facilitates proper integration between
  1574. * multiple modules. For example, module developers are familiar with the
  1575. * relative order in which hook_form_alter() implementations and #process
  1576. * functions run. A custom traversal function that affects the building of a
  1577. * form is likely to not integrate with hook_form_alter() and #process in the
  1578. * expected way. Also, deep recursion within PHP is both slow and memory
  1579. * intensive, so it is best to minimize how often it's done.
  1580. *
  1581. * As stated above, each element's #process functions are executed after its
  1582. * #value has been set. This enables those functions to execute conditional
  1583. * logic based on the current value. However, all of form_builder() runs before
  1584. * drupal_validate_form() is called, so during #process function execution, the
  1585. * element's #value has not yet been validated, so any code that requires
  1586. * validated values must reside within a submit handler.
  1587. *
  1588. * As a security measure, user input is used for an element's #value only if the
  1589. * element exists within $form, is not disabled (as per the #disabled property),
  1590. * and can be accessed (as per the #access property, except that forms submitted
  1591. * using drupal_form_submit() bypass #access restrictions). When user input is
  1592. * ignored due to #disabled and #access restrictions, the element's default
  1593. * value is used.
  1594. *
  1595. * Because of the preorder traversal, where #process functions of an element run
  1596. * before user input for its child elements is processed, and because of the
  1597. * Form API security of user input processing with respect to #access and
  1598. * #disabled described above, this generally means that #process functions
  1599. * should not use an element's (unvalidated) #value to affect the #disabled or
  1600. * #access of child elements. Use-cases where a developer may be tempted to
  1601. * implement such conditional logic usually fall into one of two categories:
  1602. * - Where user input from the current submission must affect the structure of a
  1603. * form, including properties like #access and #disabled that affect how the
  1604. * next submission needs to be processed, a multi-step workflow is needed.
  1605. * This is most commonly implemented with a submit handler setting persistent
  1606. * data within $form_state based on *validated* values in
  1607. * $form_state['values'] and setting $form_state['rebuild']. The form building
  1608. * functions must then be implemented to use the $form_state data to rebuild
  1609. * the form with the structure appropriate for the new state.
  1610. * - Where user input must affect the rendering of the form without affecting
  1611. * its structure, the necessary conditional rendering logic should reside
  1612. * within functions that run during the rendering phase (#pre_render, #theme,
  1613. * #theme_wrappers, and #post_render).
  1614. *
  1615. * @param $form_id
  1616. * A unique string identifying the form for validation, submission,
  1617. * theming, and hook_form_alter functions.
  1618. * @param $element
  1619. * An associative array containing the structure of the current element.
  1620. * @param $form_state
  1621. * A keyed array containing the current state of the form. In this
  1622. * context, it is used to accumulate information about which button
  1623. * was clicked when the form was submitted, as well as the sanitized
  1624. * $_POST data.
  1625. */
  1626. function form_builder($form_id, &$element, &$form_state) {
  1627. // Initialize as unprocessed.
  1628. $element['#processed'] = FALSE;
  1629. // Use element defaults.
  1630. if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
  1631. // Overlay $info onto $element, retaining preexisting keys in $element.
  1632. $element += $info;
  1633. $element['#defaults_loaded'] = TRUE;
  1634. }
  1635. // Assign basic defaults common for all form elements.
  1636. $element += array(
  1637. '#required' => FALSE,
  1638. '#attributes' => array(),
  1639. '#title_display' => 'before',
  1640. );
  1641. // Special handling if we're on the top level form element.
  1642. if (isset($element['#type']) && $element['#type'] == 'form') {
  1643. if (!empty($element['#https']) && variable_get('https', FALSE) &&
  1644. !url_is_external($element['#action'])) {
  1645. global $base_root;
  1646. // Not an external URL so ensure that it is secure.
  1647. $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
  1648. }
  1649. // Store a reference to the complete form in $form_state prior to building
  1650. // the form. This allows advanced #process and #after_build callbacks to
  1651. // perform changes elsewhere in the form.
  1652. $form_state['complete form'] = &$element;
  1653. // Set a flag if we have a correct form submission. This is always TRUE for
  1654. // programmed forms coming from drupal_form_submit(), or if the form_id coming
  1655. // from the POST data is set and matches the current form_id.
  1656. if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
  1657. $form_state['process_input'] = TRUE;
  1658. }
  1659. else {
  1660. $form_state['process_input'] = FALSE;
  1661. }
  1662. // All form elements should have an #array_parents property.
  1663. $element['#array_parents'] = array();
  1664. }
  1665. if (!isset($element['#id'])) {
  1666. $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
  1667. }
  1668. // Handle input elements.
  1669. if (!empty($element['#input'])) {
  1670. _form_builder_handle_input_element($form_id, $element, $form_state);
  1671. }
  1672. // Allow for elements to expand to multiple elements, e.g., radios,
  1673. // checkboxes and files.
  1674. if (isset($element['#process']) && !$element['#processed']) {
  1675. foreach ($element['#process'] as $process) {
  1676. $element = $process($element, $form_state, $form_state['complete form']);
  1677. }
  1678. $element['#processed'] = TRUE;
  1679. }
  1680. // We start off assuming all form elements are in the correct order.
  1681. $element['#sorted'] = TRUE;
  1682. // Recurse through all child elements.
  1683. $count = 0;
  1684. foreach (element_children($element) as $key) {
  1685. // Prior to checking properties of child elements, their default properties
  1686. // need to be loaded.
  1687. if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = element_info($element[$key]['#type']))) {
  1688. $element[$key] += $info;
  1689. $element[$key]['#defaults_loaded'] = TRUE;
  1690. }
  1691. // Don't squash an existing tree value.
  1692. if (!isset($element[$key]['#tree'])) {
  1693. $element[$key]['#tree'] = $element['#tree'];
  1694. }
  1695. // Deny access to child elements if parent is denied.
  1696. if (isset($element['#access']) && !$element['#access']) {
  1697. $element[$key]['#access'] = FALSE;
  1698. }
  1699. // Make child elements inherit their parent's #disabled and #allow_focus
  1700. // values unless they specify their own.
  1701. foreach (array('#disabled', '#allow_focus') as $property) {
  1702. if (isset($element[$property]) && !isset($element[$key][$property])) {
  1703. $element[$key][$property] = $element[$property];
  1704. }
  1705. }
  1706. // Don't squash existing parents value.
  1707. if (!isset($element[$key]['#parents'])) {
  1708. // Check to see if a tree of child elements is present. If so,
  1709. // continue down the tree if required.
  1710. $element[$key]['#parents'] = $element[$key]['#tree'] && $element['#tree'] ? array_merge($element['#parents'], array($key)) : array($key);
  1711. }
  1712. // Ensure #array_parents follows the actual form structure.
  1713. $array_parents = $element['#array_parents'];
  1714. $array_parents[] = $key;
  1715. $element[$key]['#array_parents'] = $array_parents;
  1716. // Assign a decimal placeholder weight to preserve original array order.
  1717. if (!isset($element[$key]['#weight'])) {
  1718. $element[$key]['#weight'] = $count/1000;
  1719. }
  1720. else {
  1721. // If one of the child elements has a weight then we will need to sort
  1722. // later.
  1723. unset($element['#sorted']);
  1724. }
  1725. $element[$key] = form_builder($form_id, $element[$key], $form_state);
  1726. $count++;
  1727. }
  1728. // The #after_build flag allows any piece of a form to be altered
  1729. // after normal input parsing has been completed.
  1730. if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
  1731. foreach ($element['#after_build'] as $function) {
  1732. $element = $function($element, $form_state);
  1733. }
  1734. $element['#after_build_done'] = TRUE;
  1735. }
  1736. // If there is a file element, we need to flip a flag so later the
  1737. // form encoding can be set.
  1738. if (isset($element['#type']) && $element['#type'] == 'file') {
  1739. $form_state['has_file_element'] = TRUE;
  1740. }
  1741. // Final tasks for the form element after form_builder() has run for all other
  1742. // elements.
  1743. if (isset($element['#type']) && $element['#type'] == 'form') {
  1744. // If there is a file element, we set the form encoding.
  1745. if (isset($form_state['has_file_element'])) {
  1746. $element['#attributes']['enctype'] = 'multipart/form-data';
  1747. }
  1748. // If a form contains a single textfield, and the ENTER key is pressed
  1749. // within it, Internet Explorer submits the form with no POST data
  1750. // identifying any submit button. Other browsers submit POST data as though
  1751. // the user clicked the first button. Therefore, to be as consistent as we
  1752. // can be across browsers, if no 'triggering_element' has been identified
  1753. // yet, default it to the first button.
  1754. if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
  1755. $form_state['triggering_element'] = $form_state['buttons'][0];
  1756. }
  1757. // If the triggering element specifies "button-level" validation and submit
  1758. // handlers to run instead of the default form-level ones, then add those to
  1759. // the form state.
  1760. foreach (array('validate', 'submit') as $type) {
  1761. if (isset($form_state['triggering_element']['#' . $type])) {
  1762. $form_state[$type . '_handlers'] = $form_state['triggering_element']['#' . $type];
  1763. }
  1764. }
  1765. // If the triggering element executes submit handlers, then set the form
  1766. // state key that's needed for those handlers to run.
  1767. if (!empty($form_state['triggering_element']['#executes_submit_callback'])) {
  1768. $form_state['submitted'] = TRUE;
  1769. }
  1770. // Special processing if the triggering element is a button.
  1771. if (isset($form_state['triggering_element']['#button_type'])) {
  1772. // Because there are several ways in which the triggering element could
  1773. // have been determined (including from input variables set by JavaScript
  1774. // or fallback behavior implemented for IE), and because buttons often
  1775. // have their #name property not derived from their #parents property, we
  1776. // can't assume that input processing that's happened up until here has
  1777. // resulted in $form_state['values'][BUTTON_NAME] being set. But it's
  1778. // common for forms to have several buttons named 'op' and switch on
  1779. // $form_state['values']['op'] during submit handler execution.
  1780. $form_state['values'][$form_state['triggering_element']['#name']] = $form_state['triggering_element']['#value'];
  1781. // @todo Legacy support. Remove in Drupal 8.
  1782. $form_state['clicked_button'] = $form_state['triggering_element'];
  1783. }
  1784. }
  1785. return $element;
  1786. }
  1787. /**
  1788. * Adds the #name and #value properties of an input element before rendering.
  1789. */
  1790. function _form_builder_handle_input_element($form_id, &$element, &$form_state) {
  1791. if (!isset($element['#name'])) {
  1792. $name = array_shift($element['#parents']);
  1793. $element['#name'] = $name;
  1794. if ($element['#type'] == 'file') {
  1795. // To make it easier to handle $_FILES in file.inc, we place all
  1796. // file fields in the 'files' array. Also, we do not support
  1797. // nested file names.
  1798. $element['#name'] = 'files[' . $element['#name'] . ']';
  1799. }
  1800. elseif (count($element['#parents'])) {
  1801. $element['#name'] .= '[' . implode('][', $element['#parents']) . ']';
  1802. }
  1803. array_unshift($element['#parents'], $name);
  1804. }
  1805. // Setting #disabled to TRUE results in user input being ignored, regardless
  1806. // of how the element is themed or whether JavaScript is used to change the
  1807. // control's attributes. However, it's good UI to let the user know that input
  1808. // is not wanted for the control. HTML supports two attributes for this:
  1809. // http://www.w3.org/TR/html401/interact/forms.html#h-17.12. If a form wants
  1810. // to start a control off with one of these attributes for UI purposes only,
  1811. // but still allow input to be processed if it's sumitted, it can set the
  1812. // desired attribute in #attributes directly rather than using #disabled.
  1813. // However, developers should think carefully about the accessibility
  1814. // implications of doing so: if the form expects input to be enterable under
  1815. // some condition triggered by JavaScript, how would someone who has
  1816. // JavaScript disabled trigger that condition? Instead, developers should
  1817. // consider whether a multi-step form would be more appropriate (#disabled can
  1818. // be changed from step to step). If one still decides to use JavaScript to
  1819. // affect when a control is enabled, then it is best for accessibility for the
  1820. // control to be enabled in the HTML, and disabled by JavaScript on document
  1821. // ready.
  1822. if (!empty($element['#disabled'])) {
  1823. if (!empty($element['#allow_focus'])) {
  1824. $element['#attributes']['readonly'] = 'readonly';
  1825. }
  1826. else {
  1827. $element['#attributes']['disabled'] = 'disabled';
  1828. }
  1829. }
  1830. // With JavaScript or other easy hacking, input can be submitted even for
  1831. // elements with #access=FALSE or #disabled=TRUE. For security, these must
  1832. // not be processed. Forms that set #disabled=TRUE on an element do not
  1833. // expect input for the element, and even forms submitted with
  1834. // drupal_form_submit() must not be able to get around this. Forms that set
  1835. // #access=FALSE on an element usually allow access for some users, so forms
  1836. // submitted with drupal_form_submit() may bypass access restriction and be
  1837. // treated as high-privilege users instead.
  1838. $process_input = empty($element['#disabled']) && ($form_state['programmed'] || ($form_state['process_input'] && (!isset($element['#access']) || $element['#access'])));
  1839. // Set the element's #value property.
  1840. if (!isset($element['#value']) && !array_key_exists('#value', $element)) {
  1841. $value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';
  1842. if ($process_input) {
  1843. // Get the input for the current element. NULL values in the input need to
  1844. // be explicitly distinguished from missing input. (see below)
  1845. $input_exists = NULL;
  1846. $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
  1847. // For browser-submitted forms, the submitted values do not contain values
  1848. // for certain elements (empty multiple select, unchecked checkbox).
  1849. // During initial form processing, we add explicit NULL values for such
  1850. // elements in $form_state['input']. When rebuilding the form, we can
  1851. // distinguish elements having NULL input from elements that were not part
  1852. // of the initially submitted form and can therefore use default values
  1853. // for the latter, if required. Programmatically submitted forms can
  1854. // submit explicit NULL values when calling drupal_form_submit(), so we do
  1855. // not modify $form_state['input'] for them.
  1856. if (!$input_exists && !$form_state['rebuild'] && !$form_state['programmed']) {
  1857. // Add the necessary parent keys to $form_state['input'] and sets the
  1858. // element's input value to NULL.
  1859. drupal_array_set_nested_value($form_state['input'], $element['#parents'], NULL);
  1860. $input_exists = TRUE;
  1861. }
  1862. // If we have input for the current element, assign it to the #value
  1863. // property, optionally filtered through $value_callback.
  1864. if ($input_exists) {
  1865. if (function_exists($value_callback)) {
  1866. $element['#value'] = $value_callback($element, $input, $form_state);
  1867. }
  1868. if (!isset($element['#value']) && isset($input)) {
  1869. $element['#value'] = $input;
  1870. }
  1871. }
  1872. // Mark all posted values for validation.
  1873. if (isset($element['#value']) || (!empty($element['#required']))) {
  1874. $element['#needs_validation'] = TRUE;
  1875. }
  1876. }
  1877. // Load defaults.
  1878. if (!isset($element['#value'])) {
  1879. // Call #type_value without a second argument to request default_value handling.
  1880. if (function_exists($value_callback)) {
  1881. $element['#value'] = $value_callback($element, FALSE, $form_state);
  1882. }
  1883. // Final catch. If we haven't set a value yet, use the explicit default value.
  1884. // Avoid image buttons (which come with garbage value), so we only get value
  1885. // for the button actually clicked.
  1886. if (!isset($element['#value']) && empty($element['#has_garbage_value'])) {
  1887. $element['#value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
  1888. }
  1889. }
  1890. }
  1891. // Determine which element (if any) triggered the submission of the form and
  1892. // keep track of all the clickable buttons in the form for
  1893. // form_state_values_clean(). Enforce the same input processing restrictions
  1894. // as above.
  1895. if ($process_input) {
  1896. // Detect if the element triggered the submission via Ajax.
  1897. if (_form_element_triggered_scripted_submission($element, $form_state)) {
  1898. $form_state['triggering_element'] = $element;
  1899. }
  1900. // If the form was submitted by the browser rather than via Ajax, then it
  1901. // can only have been triggered by a button, and we need to determine which
  1902. // button within the constraints of how browsers provide this information.
  1903. if (isset($element['#button_type'])) {
  1904. // All buttons in the form need to be tracked for
  1905. // form_state_values_clean() and for the form_builder() code that handles
  1906. // a form submission containing no button information in $_POST.
  1907. $form_state['buttons'][] = $element;
  1908. if (_form_button_was_clicked($element, $form_state)) {
  1909. $form_state['triggering_element'] = $element;
  1910. }
  1911. }
  1912. }
  1913. // Set the element's value in $form_state['values'], but only, if its key
  1914. // does not exist yet (a #value_callback may have already populated it).
  1915. if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
  1916. form_set_value($element, $element['#value'], $form_state);
  1917. }
  1918. }
  1919. /**
  1920. * Detects if an element triggered the form submission via Ajax.
  1921. *
  1922. * This detects button or non-button controls that trigger a form submission via
  1923. * Ajax or some other scriptable environment. These environments can set the
  1924. * special input key '_triggering_element_name' to identify the triggering
  1925. * element. If the name alone doesn't identify the element uniquely, the input
  1926. * key '_triggering_element_value' may also be set to require a match on element
  1927. * value. An example where this is needed is if there are several buttons all
  1928. * named 'op', and only differing in their value.
  1929. */
  1930. function _form_element_triggered_scripted_submission($element, &$form_state) {
  1931. if (!empty($form_state['input']['_triggering_element_name']) && $element['#name'] == $form_state['input']['_triggering_element_name']) {
  1932. if (empty($form_state['input']['_triggering_element_value']) || $form_state['input']['_triggering_element_value'] == $element['#value']) {
  1933. return TRUE;
  1934. }
  1935. }
  1936. return FALSE;
  1937. }
  1938. /**
  1939. * Determines if a given button triggered the form submission.
  1940. *
  1941. * This detects button controls that trigger a form submission by being clicked
  1942. * and having the click processed by the browser rather than being captured by
  1943. * JavaScript. Essentially, it detects if the button's name and value are part
  1944. * of the POST data, but with extra code to deal with the convoluted way in
  1945. * which browsers submit data for image button clicks.
  1946. *
  1947. * This does not detect button clicks processed by Ajax (that is done in
  1948. * _form_element_triggered_scripted_submission()) and it does not detect form
  1949. * submissions from Internet Explorer in response to an ENTER key pressed in a
  1950. * textfield (form_builder() has extra code for that).
  1951. *
  1952. * Because this function contains only part of the logic needed to determine
  1953. * $form_state['triggering_element'], it should not be called from anywhere
  1954. * other than within the Form API. Form validation and submit handlers needing
  1955. * to know which button was clicked should get that information from
  1956. * $form_state['triggering_element'].
  1957. */
  1958. function _form_button_was_clicked($element, &$form_state) {
  1959. // First detect normal 'vanilla' button clicks. Traditionally, all
  1960. // standard buttons on a form share the same name (usually 'op'),
  1961. // and the specific return value is used to determine which was
  1962. // clicked. This ONLY works as long as $form['#name'] puts the
  1963. // value at the top level of the tree of $_POST data.
  1964. if (isset($form_state['input'][$element['#name']]) && $form_state['input'][$element['#name']] == $element['#value']) {
  1965. return TRUE;
  1966. }
  1967. // When image buttons are clicked, browsers do NOT pass the form element
  1968. // value in $_POST. Instead they pass an integer representing the
  1969. // coordinates of the click on the button image. This means that image
  1970. // buttons MUST have unique $form['#name'] values, but the details of
  1971. // their $_POST data should be ignored.
  1972. elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
  1973. return TRUE;
  1974. }
  1975. return FALSE;
  1976. }
  1977. /**
  1978. * Removes internal Form API elements and buttons from submitted form values.
  1979. *
  1980. * This function can be used when a module wants to store all submitted form
  1981. * values, for example, by serializing them into a single database column. In
  1982. * such cases, all internal Form API values and all form button elements should
  1983. * not be contained, and this function allows to remove them before the module
  1984. * proceeds to storage. Next to button elements, the following internal values
  1985. * are removed:
  1986. * - form_id
  1987. * - form_token
  1988. * - form_build_id
  1989. * - op
  1990. *
  1991. * @param $form_state
  1992. * A keyed array containing the current state of the form, including
  1993. * submitted form values; altered by reference.
  1994. */
  1995. function form_state_values_clean(&$form_state) {
  1996. // Remove internal Form API values.
  1997. unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);
  1998. // Remove button values.
  1999. // form_builder() collects all button elements in a form. We remove the button
  2000. // value separately for each button element.
  2001. foreach ($form_state['buttons'] as $button) {
  2002. // Remove this button's value from the submitted form values by finding
  2003. // the value corresponding to this button.
  2004. // We iterate over the #parents of this button and move a reference to
  2005. // each parent in $form_state['values']. For example, if #parents is:
  2006. // array('foo', 'bar', 'baz')
  2007. // then the corresponding $form_state['values'] part will look like this:
  2008. // array(
  2009. // 'foo' => array(
  2010. // 'bar' => array(
  2011. // 'baz' => 'button_value',
  2012. // ),
  2013. // ),
  2014. // )
  2015. // We start by (re)moving 'baz' to $last_parent, so we are able unset it
  2016. // at the end of the iteration. Initially, $values will contain a
  2017. // reference to $form_state['values'], but in the iteration we move the
  2018. // reference to $form_state['values']['foo'], and finally to
  2019. // $form_state['values']['foo']['bar'], which is the level where we can
  2020. // unset 'baz' (that is stored in $last_parent).
  2021. $parents = $button['#parents'];
  2022. $values = &$form_state['values'];
  2023. $last_parent = array_pop($parents);
  2024. foreach ($parents as $parent) {
  2025. $values = &$values[$parent];
  2026. }
  2027. unset($values[$last_parent]);
  2028. }
  2029. }
  2030. /**
  2031. * Determines the value for an image button form element.
  2032. *
  2033. * @param $form
  2034. * The form element whose value is being populated.
  2035. * @param $input
  2036. * The incoming input to populate the form element. If this is FALSE,
  2037. * the element's default value should be returned.
  2038. * @param $form_state
  2039. * A keyed array containing the current state of the form.
  2040. *
  2041. * @return
  2042. * The data that will appear in the $form_state['values'] collection
  2043. * for this element. Return nothing to use the default.
  2044. */
  2045. function form_type_image_button_value($form, $input, $form_state) {
  2046. if ($input !== FALSE) {
  2047. if (!empty($input)) {
  2048. // If we're dealing with Mozilla or Opera, we're lucky. It will
  2049. // return a proper value, and we can get on with things.
  2050. return $form['#return_value'];
  2051. }
  2052. else {
  2053. // Unfortunately, in IE we never get back a proper value for THIS
  2054. // form element. Instead, we get back two split values: one for the
  2055. // X and one for the Y coordinates on which the user clicked the
  2056. // button. We'll find this element in the #post data, and search
  2057. // in the same spot for its name, with '_x'.
  2058. $input = $form_state['input'];
  2059. foreach (explode('[', $form['#name']) as $element_name) {
  2060. // chop off the ] that may exist.
  2061. if (substr($element_name, -1) == ']') {
  2062. $element_name = substr($element_name, 0, -1);
  2063. }
  2064. if (!isset($input[$element_name])) {
  2065. if (isset($input[$element_name . '_x'])) {
  2066. return $form['#return_value'];
  2067. }
  2068. return NULL;
  2069. }
  2070. $input = $input[$element_name];
  2071. }
  2072. return $form['#return_value'];
  2073. }
  2074. }
  2075. }
  2076. /**
  2077. * Determines the value for a checkbox form element.
  2078. *
  2079. * @param $form
  2080. * The form element whose value is being populated.
  2081. * @param $input
  2082. * The incoming input to populate the form element. If this is FALSE,
  2083. * the element's default value should be returned.
  2084. *
  2085. * @return
  2086. * The data that will appear in the $element_state['values'] collection
  2087. * for this element. Return nothing to use the default.
  2088. */
  2089. function form_type_checkbox_value($element, $input = FALSE) {
  2090. if ($input === FALSE) {
  2091. // Use #default_value as the default value of a checkbox, except change
  2092. // NULL to 0, because _form_builder_handle_input_element() would otherwise
  2093. // replace NULL with empty string, but an empty string is a potentially
  2094. // valid value for a checked checkbox.
  2095. return isset($element['#default_value']) ? $element['#default_value'] : 0;
  2096. }
  2097. else {
  2098. // Checked checkboxes are submitted with a value (possibly '0' or ''):
  2099. // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
  2100. // For checked checkboxes, browsers submit the string version of
  2101. // #return_value, but we return the original #return_value. For unchecked
  2102. // checkboxes, browsers submit nothing at all, but
  2103. // _form_builder_handle_input_element() detects this, and calls this
  2104. // function with $input=NULL. Returning NULL from a value callback means to
  2105. // use the default value, which is not what is wanted when an unchecked
  2106. // checkbox is submitted, so we use integer 0 as the value indicating an
  2107. // unchecked checkbox. Therefore, modules must not use integer 0 as a
  2108. // #return_value, as doing so results in the checkbox always being treated
  2109. // as unchecked. The string '0' is allowed for #return_value. The most
  2110. // common use-case for setting #return_value to either 0 or '0' is for the
  2111. // first option within a 0-indexed array of checkboxes, and for this,
  2112. // form_process_checkboxes() uses the string rather than the integer.
  2113. return isset($input) ? $element['#return_value'] : 0;
  2114. }
  2115. }
  2116. /**
  2117. * Determines the value for a checkboxes form element.
  2118. *
  2119. * @param $element
  2120. * The form element whose value is being populated.
  2121. * @param $input
  2122. * The incoming input to populate the form element. If this is FALSE,
  2123. * the element's default value should be returned.
  2124. *
  2125. * @return
  2126. * The data that will appear in the $element_state['values'] collection
  2127. * for this element. Return nothing to use the default.
  2128. */
  2129. function form_type_checkboxes_value($element, $input = FALSE) {
  2130. if ($input === FALSE) {
  2131. $value = array();
  2132. $element += array('#default_value' => array());
  2133. foreach ($element['#default_value'] as $key) {
  2134. $value[$key] = $key;
  2135. }
  2136. return $value;
  2137. }
  2138. elseif (is_array($input)) {
  2139. // Programmatic form submissions use NULL to indicate that a checkbox
  2140. // should be unchecked; see drupal_form_submit(). We therefore remove all
  2141. // NULL elements from the array before constructing the return value, to
  2142. // simulate the behavior of web browsers (which do not send unchecked
  2143. // checkboxes to the server at all). This will not affect non-programmatic
  2144. // form submissions, since all values in $_POST are strings.
  2145. foreach ($input as $key => $value) {
  2146. if (!isset($value)) {
  2147. unset($input[$key]);
  2148. }
  2149. }
  2150. return drupal_map_assoc($input);
  2151. }
  2152. else {
  2153. return array();
  2154. }
  2155. }
  2156. /**
  2157. * Determines the value for a tableselect form element.
  2158. *
  2159. * @param $element
  2160. * The form element whose value is being populated.
  2161. * @param $input
  2162. * The incoming input to populate the form element. If this is FALSE,
  2163. * the element's default value should be returned.
  2164. *
  2165. * @return
  2166. * The data that will appear in the $element_state['values'] collection
  2167. * for this element. Return nothing to use the default.
  2168. */
  2169. function form_type_tableselect_value($element, $input = FALSE) {
  2170. // If $element['#multiple'] == FALSE, then radio buttons are displayed and
  2171. // the default value handling is used.
  2172. if (isset($element['#multiple']) && $element['#multiple']) {
  2173. // Checkboxes are being displayed with the default value coming from the
  2174. // keys of the #default_value property. This differs from the checkboxes
  2175. // element which uses the array values.
  2176. if ($input === FALSE) {
  2177. $value = array();
  2178. $element += array('#default_value' => array());
  2179. foreach ($element['#default_value'] as $key => $flag) {
  2180. if ($flag) {
  2181. $value[$key] = $key;
  2182. }
  2183. }
  2184. return $value;
  2185. }
  2186. else {
  2187. return is_array($input) ? drupal_map_assoc($input) : array();
  2188. }
  2189. }
  2190. }
  2191. /**
  2192. * Form value callback: Determines the value for a #type radios form element.
  2193. *
  2194. * @param $element
  2195. * The form element whose value is being populated.
  2196. * @param $input
  2197. * (optional) The incoming input to populate the form element. If FALSE, the
  2198. * element's default value is returned. Defaults to FALSE.
  2199. *
  2200. * @return
  2201. * The data that will appear in the $element_state['values'] collection for
  2202. * this element.
  2203. */
  2204. function form_type_radios_value(&$element, $input = FALSE) {
  2205. if ($input !== FALSE) {
  2206. // There may not be a submitted value for multiple radio buttons, if none of
  2207. // the options was checked by default. If there is no submitted input value
  2208. // for this element (NULL), _form_builder_handle_input_element()
  2209. // automatically attempts to use the #default_value (if set) or an empty
  2210. // string (''). However, an empty string would fail validation in
  2211. // _form_validate(), in case it is not contained in the list of allowed
  2212. // values in #options.
  2213. if (!isset($input)) {
  2214. // Signify a garbage value to disable the #default_value handling and take
  2215. // over NULL as #value.
  2216. $element['#has_garbage_value'] = TRUE;
  2217. // There was a user submission so validation is a must. If this element is
  2218. // #required, then an appropriate error message will be output. While an
  2219. // optional #type 'radios' does not necessarily make sense from a user
  2220. // interaction perspective, there may be use-cases for that and it is not
  2221. // the job of Form API to artificially limit possibilities.
  2222. $element['#needs_validation'] = TRUE;
  2223. }
  2224. // The value stays the same, but the flags above will ensure it is
  2225. // processed properly.
  2226. return $input;
  2227. }
  2228. elseif (isset($element['#default_value'])) {
  2229. return $element['#default_value'];
  2230. }
  2231. }
  2232. /**
  2233. * Determines the value for a password_confirm form element.
  2234. *
  2235. * @param $element
  2236. * The form element whose value is being populated.
  2237. * @param $input
  2238. * The incoming input to populate the form element. If this is FALSE,
  2239. * the element's default value should be returned.
  2240. *
  2241. * @return
  2242. * The data that will appear in the $element_state['values'] collection
  2243. * for this element. Return nothing to use the default.
  2244. */
  2245. function form_type_password_confirm_value($element, $input = FALSE) {
  2246. if ($input === FALSE) {
  2247. $element += array('#default_value' => array());
  2248. return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
  2249. }
  2250. }
  2251. /**
  2252. * Determines the value for a select form element.
  2253. *
  2254. * @param $element
  2255. * The form element whose value is being populated.
  2256. * @param $input
  2257. * The incoming input to populate the form element. If this is FALSE,
  2258. * the element's default value should be returned.
  2259. *
  2260. * @return
  2261. * The data that will appear in the $element_state['values'] collection
  2262. * for this element. Return nothing to use the default.
  2263. */
  2264. function form_type_select_value($element, $input = FALSE) {
  2265. if ($input !== FALSE) {
  2266. if (isset($element['#multiple']) && $element['#multiple']) {
  2267. // If an enabled multi-select submits NULL, it means all items are
  2268. // unselected. A disabled multi-select always submits NULL, and the
  2269. // default value should be used.
  2270. if (empty($element['#disabled'])) {
  2271. return (is_array($input)) ? drupal_map_assoc($input) : array();
  2272. }
  2273. else {
  2274. return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
  2275. }
  2276. }
  2277. // Non-multiple select elements may have an empty option preprended to them
  2278. // (see form_process_select()). When this occurs, usually #empty_value is
  2279. // an empty string, but some forms set #empty_value to integer 0 or some
  2280. // other non-string constant. PHP receives all submitted form input as
  2281. // strings, but if the empty option is selected, set the value to match the
  2282. // empty value exactly.
  2283. elseif (isset($element['#empty_value']) && $input === (string) $element['#empty_value']) {
  2284. return $element['#empty_value'];
  2285. }
  2286. else {
  2287. return $input;
  2288. }
  2289. }
  2290. }
  2291. /**
  2292. * Determines the value for a textfield form element.
  2293. *
  2294. * @param $element
  2295. * The form element whose value is being populated.
  2296. * @param $input
  2297. * The incoming input to populate the form element. If this is FALSE,
  2298. * the element's default value should be returned.
  2299. *
  2300. * @return
  2301. * The data that will appear in the $element_state['values'] collection
  2302. * for this element. Return nothing to use the default.
  2303. */
  2304. function form_type_textfield_value($element, $input = FALSE) {
  2305. if ($input !== FALSE && $input !== NULL) {
  2306. // Equate $input to the form value to ensure it's marked for
  2307. // validation.
  2308. return str_replace(array("\r", "\n"), '', $input);
  2309. }
  2310. }
  2311. /**
  2312. * Determines the value for form's token value.
  2313. *
  2314. * @param $element
  2315. * The form element whose value is being populated.
  2316. * @param $input
  2317. * The incoming input to populate the form element. If this is FALSE,
  2318. * the element's default value should be returned.
  2319. *
  2320. * @return
  2321. * The data that will appear in the $element_state['values'] collection
  2322. * for this element. Return nothing to use the default.
  2323. */
  2324. function form_type_token_value($element, $input = FALSE) {
  2325. if ($input !== FALSE) {
  2326. return (string) $input;
  2327. }
  2328. }
  2329. /**
  2330. * Changes submitted form values during form validation.
  2331. *
  2332. * Use this function to change the submitted value of a form element in a form
  2333. * validation function, so that the changed value persists in $form_state
  2334. * through the remaining validation and submission handlers. It does not change
  2335. * the value in $element['#value'], only in $form_state['values'], which is
  2336. * where submitted values are always stored.
  2337. *
  2338. * Note that form validation functions are specified in the '#validate'
  2339. * component of the form array (the value of $form['#validate'] is an array of
  2340. * validation function names). If the form does not originate in your module,
  2341. * you can implement hook_form_FORM_ID_alter() to add a validation function
  2342. * to $form['#validate'].
  2343. *
  2344. * @param $element
  2345. * The form element that should have its value updated; in most cases you can
  2346. * just pass in the element from the $form array, although the only component
  2347. * that is actually used is '#parents'. If constructing yourself, set
  2348. * $element['#parents'] to be an array giving the path through the form
  2349. * array's keys to the element whose value you want to update. For instance,
  2350. * if you want to update the value of $form['elem1']['elem2'], which should be
  2351. * stored in $form_state['values']['elem1']['elem2'], you would set
  2352. * $element['#parents'] = array('elem1','elem2').
  2353. * @param $value
  2354. * The new value for the form element.
  2355. * @param $form_state
  2356. * Form state array where the value change should be recorded.
  2357. */
  2358. function form_set_value($element, $value, &$form_state) {
  2359. drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
  2360. }
  2361. /**
  2362. * Allows PHP array processing of multiple select options with the same value.
  2363. *
  2364. * Used for form select elements which need to validate HTML option groups
  2365. * and multiple options which may return the same value. Associative PHP arrays
  2366. * cannot handle these structures, since they share a common key.
  2367. *
  2368. * @param $array
  2369. * The form options array to process.
  2370. *
  2371. * @return
  2372. * An array with all hierarchical elements flattened to a single array.
  2373. */
  2374. function form_options_flatten($array) {
  2375. // Always reset static var when first entering the recursion.
  2376. drupal_static_reset('_form_options_flatten');
  2377. return _form_options_flatten($array);
  2378. }
  2379. /**
  2380. * Iterates over an array and returns a flat array with duplicate keys removed.
  2381. *
  2382. * This function also handles cases where objects are passed as array values.
  2383. */
  2384. function _form_options_flatten($array) {
  2385. $return = &drupal_static(__FUNCTION__);
  2386. foreach ($array as $key => $value) {
  2387. if (is_object($value)) {
  2388. _form_options_flatten($value->option);
  2389. }
  2390. elseif (is_array($value)) {
  2391. _form_options_flatten($value);
  2392. }
  2393. else {
  2394. $return[$key] = 1;
  2395. }
  2396. }
  2397. return $return;
  2398. }
  2399. /**
  2400. * Processes a select list form element.
  2401. *
  2402. * This process callback is mandatory for select fields, since all user agents
  2403. * automatically preselect the first available option of single (non-multiple)
  2404. * select lists.
  2405. *
  2406. * @param $element
  2407. * The form element to process. Properties used:
  2408. * - #multiple: (optional) Indicates whether one or more options can be
  2409. * selected. Defaults to FALSE.
  2410. * - #default_value: Must be NULL or not set in case there is no value for the
  2411. * element yet, in which case a first default option is inserted by default.
  2412. * Whether this first option is a valid option depends on whether the field
  2413. * is #required or not.
  2414. * - #required: (optional) Whether the user needs to select an option (TRUE)
  2415. * or not (FALSE). Defaults to FALSE.
  2416. * - #empty_option: (optional) The label to show for the first default option.
  2417. * By default, the label is automatically set to "- Please select -" for a
  2418. * required field and "- None -" for an optional field.
  2419. * - #empty_value: (optional) The value for the first default option, which is
  2420. * used to determine whether the user submitted a value or not.
  2421. * - If #required is TRUE, this defaults to '' (an empty string).
  2422. * - If #required is not TRUE and this value isn't set, then no extra option
  2423. * is added to the select control, leaving the control in a slightly
  2424. * illogical state, because there's no way for the user to select nothing,
  2425. * since all user agents automatically preselect the first available
  2426. * option. But people are used to this being the behavior of select
  2427. * controls.
  2428. * @todo Address the above issue in Drupal 8.
  2429. * - If #required is not TRUE and this value is set (most commonly to an
  2430. * empty string), then an extra option (see #empty_option above)
  2431. * representing a "non-selection" is added with this as its value.
  2432. *
  2433. * @see _form_validate()
  2434. */
  2435. function form_process_select($element) {
  2436. // #multiple select fields need a special #name.
  2437. if ($element['#multiple']) {
  2438. $element['#attributes']['multiple'] = 'multiple';
  2439. $element['#attributes']['name'] = $element['#name'] . '[]';
  2440. }
  2441. // A non-#multiple select needs special handling to prevent user agents from
  2442. // preselecting the first option without intention. #multiple select lists do
  2443. // not get an empty option, as it would not make sense, user interface-wise.
  2444. else {
  2445. $required = $element['#required'];
  2446. // If the element is required and there is no #default_value, then add an
  2447. // empty option that will fail validation, so that the user is required to
  2448. // make a choice. Also, if there's a value for #empty_value or
  2449. // #empty_option, then add an option that represents emptiness.
  2450. if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  2451. $element += array(
  2452. '#empty_value' => '',
  2453. '#empty_option' => $required ? t('- Select -') : t('- None -'),
  2454. );
  2455. // The empty option is prepended to #options and purposively not merged
  2456. // to prevent another option in #options mistakenly using the same value
  2457. // as #empty_value.
  2458. $empty_option = array($element['#empty_value'] => $element['#empty_option']);
  2459. $element['#options'] = $empty_option + $element['#options'];
  2460. }
  2461. }
  2462. return $element;
  2463. }
  2464. /**
  2465. * Returns HTML for a select form element.
  2466. *
  2467. * It is possible to group options together; to do this, change the format of
  2468. * $options to an associative array in which the keys are group labels, and the
  2469. * values are associative arrays in the normal $options format.
  2470. *
  2471. * @param $variables
  2472. * An associative array containing:
  2473. * - element: An associative array containing the properties of the element.
  2474. * Properties used: #title, #value, #options, #description, #extra,
  2475. * #multiple, #required, #name, #attributes, #size.
  2476. *
  2477. * @ingroup themeable
  2478. */
  2479. function theme_select($variables) {
  2480. $element = $variables['element'];
  2481. element_set_attributes($element, array('id', 'name', 'size'));
  2482. _form_set_class($element, array('form-select'));
  2483. return '<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>';
  2484. }
  2485. /**
  2486. * Converts a select form element's options array into HTML.
  2487. *
  2488. * @param $element
  2489. * An associative array containing the properties of the element.
  2490. * @param $choices
  2491. * Mixed: Either an associative array of items to list as choices, or an
  2492. * object with an 'option' member that is an associative array. This
  2493. * parameter is only used internally and should not be passed.
  2494. *
  2495. * @return
  2496. * An HTML string of options for the select form element.
  2497. */
  2498. function form_select_options($element, $choices = NULL) {
  2499. if (!isset($choices)) {
  2500. $choices = $element['#options'];
  2501. }
  2502. // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  2503. // isset() fails in this situation.
  2504. $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  2505. $value_is_array = $value_valid && is_array($element['#value']);
  2506. $options = '';
  2507. foreach ($choices as $key => $choice) {
  2508. if (is_array($choice)) {
  2509. $options .= '<optgroup label="' . $key . '">';
  2510. $options .= form_select_options($element, $choice);
  2511. $options .= '</optgroup>';
  2512. }
  2513. elseif (is_object($choice)) {
  2514. $options .= form_select_options($element, $choice->option);
  2515. }
  2516. else {
  2517. $key = (string) $key;
  2518. if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
  2519. $selected = ' selected="selected"';
  2520. }
  2521. else {
  2522. $selected = '';
  2523. }
  2524. $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
  2525. }
  2526. }
  2527. return $options;
  2528. }
  2529. /**
  2530. * Returns the indexes of a select element's options matching a given key.
  2531. *
  2532. * This function is useful if you need to modify the options that are
  2533. * already in a form element; for example, to remove choices which are
  2534. * not valid because of additional filters imposed by another module.
  2535. * One example might be altering the choices in a taxonomy selector.
  2536. * To correctly handle the case of a multiple hierarchy taxonomy,
  2537. * #options arrays can now hold an array of objects, instead of a
  2538. * direct mapping of keys to labels, so that multiple choices in the
  2539. * selector can have the same key (and label). This makes it difficult
  2540. * to manipulate directly, which is why this helper function exists.
  2541. *
  2542. * This function does not support optgroups (when the elements of the
  2543. * #options array are themselves arrays), and will return FALSE if
  2544. * arrays are found. The caller must either flatten/restore or
  2545. * manually do their manipulations in this case, since returning the
  2546. * index is not sufficient, and supporting this would make the
  2547. * "helper" too complicated and cumbersome to be of any help.
  2548. *
  2549. * As usual with functions that can return array() or FALSE, do not
  2550. * forget to use === and !== if needed.
  2551. *
  2552. * @param $element
  2553. * The select element to search.
  2554. * @param $key
  2555. * The key to look for.
  2556. *
  2557. * @return
  2558. * An array of indexes that match the given $key. Array will be
  2559. * empty if no elements were found. FALSE if optgroups were found.
  2560. */
  2561. function form_get_options($element, $key) {
  2562. $keys = array();
  2563. foreach ($element['#options'] as $index => $choice) {
  2564. if (is_array($choice)) {
  2565. return FALSE;
  2566. }
  2567. elseif (is_object($choice)) {
  2568. if (isset($choice->option[$key])) {
  2569. $keys[] = $index;
  2570. }
  2571. }
  2572. elseif ($index == $key) {
  2573. $keys[] = $index;
  2574. }
  2575. }
  2576. return $keys;
  2577. }
  2578. /**
  2579. * Returns HTML for a fieldset form element and its children.
  2580. *
  2581. * @param $variables
  2582. * An associative array containing:
  2583. * - element: An associative array containing the properties of the element.
  2584. * Properties used: #attributes, #children, #collapsed, #collapsible,
  2585. * #description, #id, #title, #value.
  2586. *
  2587. * @ingroup themeable
  2588. */
  2589. function theme_fieldset($variables) {
  2590. $element = $variables['element'];
  2591. element_set_attributes($element, array('id'));
  2592. _form_set_class($element, array('form-wrapper'));
  2593. $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  2594. if (!empty($element['#title'])) {
  2595. // Always wrap fieldset legends in a SPAN for CSS positioning.
  2596. $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
  2597. }
  2598. $output .= '<div class="fieldset-wrapper">';
  2599. if (!empty($element['#description'])) {
  2600. $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  2601. }
  2602. $output .= $element['#children'];
  2603. if (isset($element['#value'])) {
  2604. $output .= $element['#value'];
  2605. }
  2606. $output .= '</div>';
  2607. $output .= "</fieldset>\n";
  2608. return $output;
  2609. }
  2610. /**
  2611. * Returns HTML for a radio button form element.
  2612. *
  2613. * Note: The input "name" attribute needs to be sanitized before output, which
  2614. * is currently done by passing all attributes to drupal_attributes().
  2615. *
  2616. * @param $variables
  2617. * An associative array containing:
  2618. * - element: An associative array containing the properties of the element.
  2619. * Properties used: #required, #return_value, #value, #attributes, #title,
  2620. * #description
  2621. *
  2622. * @ingroup themeable
  2623. */
  2624. function theme_radio($variables) {
  2625. $element = $variables['element'];
  2626. $element['#attributes']['type'] = 'radio';
  2627. element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
  2628. if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
  2629. $element['#attributes']['checked'] = 'checked';
  2630. }
  2631. _form_set_class($element, array('form-radio'));
  2632. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  2633. }
  2634. /**
  2635. * Returns HTML for a set of radio button form elements.
  2636. *
  2637. * @param $variables
  2638. * An associative array containing:
  2639. * - element: An associative array containing the properties of the element.
  2640. * Properties used: #title, #value, #options, #description, #required,
  2641. * #attributes, #children.
  2642. *
  2643. * @ingroup themeable
  2644. */
  2645. function theme_radios($variables) {
  2646. $element = $variables['element'];
  2647. $attributes = array();
  2648. if (isset($element['#id'])) {
  2649. $attributes['id'] = $element['#id'];
  2650. }
  2651. $attributes['class'] = 'form-radios';
  2652. if (!empty($element['#attributes']['class'])) {
  2653. $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  2654. }
  2655. if (isset($element['#attributes']['title'])) {
  2656. $attributes['title'] = $element['#attributes']['title'];
  2657. }
  2658. return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
  2659. }
  2660. /**
  2661. * Expand a password_confirm field into two text boxes.
  2662. */
  2663. function form_process_password_confirm($element) {
  2664. $element['pass1'] = array(
  2665. '#type' => 'password',
  2666. '#title' => t('Password'),
  2667. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
  2668. '#required' => $element['#required'],
  2669. '#attributes' => array('class' => array('password-field')),
  2670. );
  2671. $element['pass2'] = array(
  2672. '#type' => 'password',
  2673. '#title' => t('Confirm password'),
  2674. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
  2675. '#required' => $element['#required'],
  2676. '#attributes' => array('class' => array('password-confirm')),
  2677. );
  2678. $element['#element_validate'] = array('password_confirm_validate');
  2679. $element['#tree'] = TRUE;
  2680. if (isset($element['#size'])) {
  2681. $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  2682. }
  2683. return $element;
  2684. }
  2685. /**
  2686. * Validates a password_confirm element.
  2687. */
  2688. function password_confirm_validate($element, &$element_state) {
  2689. $pass1 = trim($element['pass1']['#value']);
  2690. $pass2 = trim($element['pass2']['#value']);
  2691. if (!empty($pass1) || !empty($pass2)) {
  2692. if (strcmp($pass1, $pass2)) {
  2693. form_error($element, t('The specified passwords do not match.'));
  2694. }
  2695. }
  2696. elseif ($element['#required'] && !empty($element_state['input'])) {
  2697. form_error($element, t('Password field is required.'));
  2698. }
  2699. // Password field must be converted from a two-element array into a single
  2700. // string regardless of validation results.
  2701. form_set_value($element['pass1'], NULL, $element_state);
  2702. form_set_value($element['pass2'], NULL, $element_state);
  2703. form_set_value($element, $pass1, $element_state);
  2704. return $element;
  2705. }
  2706. /**
  2707. * Returns HTML for a date selection form element.
  2708. *
  2709. * @param $variables
  2710. * An associative array containing:
  2711. * - element: An associative array containing the properties of the element.
  2712. * Properties used: #title, #value, #options, #description, #required,
  2713. * #attributes.
  2714. *
  2715. * @ingroup themeable
  2716. */
  2717. function theme_date($variables) {
  2718. $element = $variables['element'];
  2719. $attributes = array();
  2720. if (isset($element['#id'])) {
  2721. $attributes['id'] = $element['#id'];
  2722. }
  2723. if (!empty($element['#attributes']['class'])) {
  2724. $attributes['class'] = (array) $element['#attributes']['class'];
  2725. }
  2726. $attributes['class'][] = 'container-inline';
  2727. return '<div' . drupal_attributes($attributes) . '>' . drupal_render_children($element) . '</div>';
  2728. }
  2729. /**
  2730. * Expands a date element into year, month, and day select elements.
  2731. */
  2732. function form_process_date($element) {
  2733. // Default to current date
  2734. if (empty($element['#value'])) {
  2735. $element['#value'] = array(
  2736. 'day' => format_date(REQUEST_TIME, 'custom', 'j'),
  2737. 'month' => format_date(REQUEST_TIME, 'custom', 'n'),
  2738. 'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
  2739. );
  2740. }
  2741. $element['#tree'] = TRUE;
  2742. // Determine the order of day, month, year in the site's chosen date format.
  2743. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  2744. $sort = array();
  2745. $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
  2746. $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
  2747. $sort['year'] = strpos($format, 'Y');
  2748. asort($sort);
  2749. $order = array_keys($sort);
  2750. // Output multi-selector for date.
  2751. foreach ($order as $type) {
  2752. switch ($type) {
  2753. case 'day':
  2754. $options = drupal_map_assoc(range(1, 31));
  2755. $title = t('Day');
  2756. break;
  2757. case 'month':
  2758. $options = drupal_map_assoc(range(1, 12), 'map_month');
  2759. $title = t('Month');
  2760. break;
  2761. case 'year':
  2762. $options = drupal_map_assoc(range(1900, 2050));
  2763. $title = t('Year');
  2764. break;
  2765. }
  2766. $element[$type] = array(
  2767. '#type' => 'select',
  2768. '#title' => $title,
  2769. '#title_display' => 'invisible',
  2770. '#value' => $element['#value'][$type],
  2771. '#attributes' => $element['#attributes'],
  2772. '#options' => $options,
  2773. );
  2774. }
  2775. return $element;
  2776. }
  2777. /**
  2778. * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
  2779. */
  2780. function date_validate($element) {
  2781. if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
  2782. form_error($element, t('The specified date is invalid.'));
  2783. }
  2784. }
  2785. /**
  2786. * Helper function for usage with drupal_map_assoc to display month names.
  2787. */
  2788. function map_month($month) {
  2789. $months = &drupal_static(__FUNCTION__, array(
  2790. 1 => 'Jan',
  2791. 2 => 'Feb',
  2792. 3 => 'Mar',
  2793. 4 => 'Apr',
  2794. 5 => 'May',
  2795. 6 => 'Jun',
  2796. 7 => 'Jul',
  2797. 8 => 'Aug',
  2798. 9 => 'Sep',
  2799. 10 => 'Oct',
  2800. 11 => 'Nov',
  2801. 12 => 'Dec',
  2802. ));
  2803. return t($months[$month]);
  2804. }
  2805. /**
  2806. * Sets the value for a weight element, with zero as a default.
  2807. */
  2808. function weight_value(&$form) {
  2809. if (isset($form['#default_value'])) {
  2810. $form['#value'] = $form['#default_value'];
  2811. }
  2812. else {
  2813. $form['#value'] = 0;
  2814. }
  2815. }
  2816. /**
  2817. * Expands a radios element into individual radio elements.
  2818. */
  2819. function form_process_radios($element) {
  2820. if (count($element['#options']) > 0) {
  2821. $weight = 0;
  2822. foreach ($element['#options'] as $key => $choice) {
  2823. // Maintain order of options as defined in #options, in case the element
  2824. // defines custom option sub-elements, but does not define all option
  2825. // sub-elements.
  2826. $weight += 0.001;
  2827. $element += array($key => array());
  2828. // Generate the parents as the autogenerator does, so we will have a
  2829. // unique id for each radio button.
  2830. $parents_for_id = array_merge($element['#parents'], array($key));
  2831. $element[$key] += array(
  2832. '#type' => 'radio',
  2833. '#title' => $choice,
  2834. // The key is sanitized in drupal_attributes() during output from the
  2835. // theme function.
  2836. '#return_value' => $key,
  2837. // Use default or FALSE. A value of FALSE means that the radio button is
  2838. // not 'checked'.
  2839. '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : FALSE,
  2840. '#attributes' => $element['#attributes'],
  2841. '#parents' => $element['#parents'],
  2842. '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
  2843. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  2844. '#weight' => $weight,
  2845. );
  2846. }
  2847. }
  2848. return $element;
  2849. }
  2850. /**
  2851. * Returns HTML for a checkbox form element.
  2852. *
  2853. * @param $variables
  2854. * An associative array containing:
  2855. * - element: An associative array containing the properties of the element.
  2856. * Properties used: #title, #value, #return_value, #description, #required,
  2857. * #attributes, #checked.
  2858. *
  2859. * @ingroup themeable
  2860. */
  2861. function theme_checkbox($variables) {
  2862. $element = $variables['element'];
  2863. $t = get_t();
  2864. $element['#attributes']['type'] = 'checkbox';
  2865. element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
  2866. // Unchecked checkbox has #value of integer 0.
  2867. if (!empty($element['#checked'])) {
  2868. $element['#attributes']['checked'] = 'checked';
  2869. }
  2870. _form_set_class($element, array('form-checkbox'));
  2871. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  2872. }
  2873. /**
  2874. * Returns HTML for a set of checkbox form elements.
  2875. *
  2876. * @param $variables
  2877. * An associative array containing:
  2878. * - element: An associative array containing the properties of the element.
  2879. * Properties used: #children, #attributes.
  2880. *
  2881. * @ingroup themeable
  2882. */
  2883. function theme_checkboxes($variables) {
  2884. $element = $variables['element'];
  2885. $attributes = array();
  2886. if (isset($element['#id'])) {
  2887. $attributes['id'] = $element['#id'];
  2888. }
  2889. $attributes['class'][] = 'form-checkboxes';
  2890. if (!empty($element['#attributes']['class'])) {
  2891. $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  2892. }
  2893. if (isset($element['#attributes']['title'])) {
  2894. $attributes['title'] = $element['#attributes']['title'];
  2895. }
  2896. return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
  2897. }
  2898. /**
  2899. * Adds form element theming to an element if its title or description is set.
  2900. *
  2901. * This is used as a pre render function for checkboxes and radios.
  2902. */
  2903. function form_pre_render_conditional_form_element($element) {
  2904. $t = get_t();
  2905. // Set the element's title attribute to show #title as a tooltip, if needed.
  2906. if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
  2907. $element['#attributes']['title'] = $element['#title'];
  2908. if (!empty($element['#required'])) {
  2909. // Append an indication that this field is required.
  2910. $element['#attributes']['title'] .= ' (' . $t('Required') . ')';
  2911. }
  2912. }
  2913. if (isset($element['#title']) || isset($element['#description'])) {
  2914. $element['#theme_wrappers'][] = 'form_element';
  2915. }
  2916. return $element;
  2917. }
  2918. /**
  2919. * Sets the #checked property of a checkbox element.
  2920. */
  2921. function form_process_checkbox($element, $form_state) {
  2922. $value = $element['#value'];
  2923. $return_value = $element['#return_value'];
  2924. // On form submission, the #value of an available and enabled checked
  2925. // checkbox is #return_value, and the #value of an available and enabled
  2926. // unchecked checkbox is integer 0. On not submitted forms, and for
  2927. // checkboxes with #access=FALSE or #disabled=TRUE, the #value is
  2928. // #default_value (integer 0 if #default_value is NULL). Most of the time,
  2929. // a string comparison of #value and #return_value is sufficient for
  2930. // determining the "checked" state, but a value of TRUE always means checked
  2931. // (even if #return_value is 'foo'), and a value of FALSE or integer 0 always
  2932. // means unchecked (even if #return_value is '' or '0').
  2933. if ($value === TRUE || $value === FALSE || $value === 0) {
  2934. $element['#checked'] = (bool) $value;
  2935. }
  2936. else {
  2937. // Compare as strings, so that 15 is not considered equal to '15foo', but 1
  2938. // is considered equal to '1'. This cast does not imply that either #value
  2939. // or #return_value is expected to be a string.
  2940. $element['#checked'] = ((string) $value === (string) $return_value);
  2941. }
  2942. return $element;
  2943. }
  2944. /**
  2945. * Processes a checkboxes form element.
  2946. */
  2947. function form_process_checkboxes($element) {
  2948. $value = is_array($element['#value']) ? $element['#value'] : array();
  2949. $element['#tree'] = TRUE;
  2950. if (count($element['#options']) > 0) {
  2951. if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
  2952. $element['#default_value'] = array();
  2953. }
  2954. $weight = 0;
  2955. foreach ($element['#options'] as $key => $choice) {
  2956. // Integer 0 is not a valid #return_value, so use '0' instead.
  2957. // @see form_type_checkbox_value().
  2958. // @todo For Drupal 8, cast all integer keys to strings for consistency
  2959. // with form_process_radios().
  2960. if ($key === 0) {
  2961. $key = '0';
  2962. }
  2963. // Maintain order of options as defined in #options, in case the element
  2964. // defines custom option sub-elements, but does not define all option
  2965. // sub-elements.
  2966. $weight += 0.001;
  2967. $element += array($key => array());
  2968. $element[$key] += array(
  2969. '#type' => 'checkbox',
  2970. '#title' => $choice,
  2971. '#return_value' => $key,
  2972. '#default_value' => isset($value[$key]) ? $key : NULL,
  2973. '#attributes' => $element['#attributes'],
  2974. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  2975. '#weight' => $weight,
  2976. );
  2977. }
  2978. }
  2979. return $element;
  2980. }
  2981. /**
  2982. * Processes a form actions container element.
  2983. *
  2984. * @param $element
  2985. * An associative array containing the properties and children of the
  2986. * form actions container.
  2987. * @param $form_state
  2988. * The $form_state array for the form this element belongs to.
  2989. *
  2990. * @return
  2991. * The processed element.
  2992. */
  2993. function form_process_actions($element, &$form_state) {
  2994. $element['#attributes']['class'][] = 'form-actions';
  2995. return $element;
  2996. }
  2997. /**
  2998. * Processes a container element.
  2999. *
  3000. * @param $element
  3001. * An associative array containing the properties and children of the
  3002. * container.
  3003. * @param $form_state
  3004. * The $form_state array for the form this element belongs to.
  3005. *
  3006. * @return
  3007. * The processed element.
  3008. */
  3009. function form_process_container($element, &$form_state) {
  3010. // Generate the ID of the element if it's not explicitly given.
  3011. if (!isset($element['#id'])) {
  3012. $element['#id'] = drupal_html_id(implode('-', $element['#parents']) . '-wrapper');
  3013. }
  3014. return $element;
  3015. }
  3016. /**
  3017. * Returns HTML to wrap child elements in a container.
  3018. *
  3019. * Used for grouped form items. Can also be used as a #theme_wrapper for any
  3020. * renderable element, to surround it with a <div> and add attributes such as
  3021. * classes or an HTML id.
  3022. *
  3023. * @param $variables
  3024. * An associative array containing:
  3025. * - element: An associative array containing the properties of the element.
  3026. * Properties used: #id, #attributes, #children.
  3027. *
  3028. * @ingroup themeable
  3029. */
  3030. function theme_container($variables) {
  3031. $element = $variables['element'];
  3032. // Special handling for form elements.
  3033. if (isset($element['#array_parents'])) {
  3034. // Assign an html ID.
  3035. if (!isset($element['#attributes']['id'])) {
  3036. $element['#attributes']['id'] = $element['#id'];
  3037. }
  3038. // Add the 'form-wrapper' class.
  3039. $element['#attributes']['class'][] = 'form-wrapper';
  3040. }
  3041. return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
  3042. }
  3043. /**
  3044. * Returns HTML for a table with radio buttons or checkboxes.
  3045. *
  3046. * An example of per-row options:
  3047. * @code
  3048. * $options = array();
  3049. * $options[0]['title'] = "A red row"
  3050. * $options[0]['#attributes'] = array ('class' => array('red-row'));
  3051. * $options[1]['title'] = "A blue row"
  3052. * $options[1]['#attributes'] = array ('class' => array('blue-row'));
  3053. *
  3054. * $form['myselector'] = array (
  3055. * '#type' => 'tableselect',
  3056. * '#title' => 'My Selector'
  3057. * '#options' => $options,
  3058. * );
  3059. * @endcode
  3060. *
  3061. * @param $variables
  3062. * An associative array containing:
  3063. * - element: An associative array containing the properties and children of
  3064. * the tableselect element. Properties used: #header, #options, #empty,
  3065. * and #js_select. The #options property is an array of selection options;
  3066. * each array element of #options is an array of properties. These
  3067. * properties can include #attributes, which is added to the
  3068. * table row's HTML attributes; see theme_table().
  3069. *
  3070. * @ingroup themeable
  3071. */
  3072. function theme_tableselect($variables) {
  3073. $element = $variables['element'];
  3074. $rows = array();
  3075. $header = $element['#header'];
  3076. if (!empty($element['#options'])) {
  3077. // Generate a table row for each selectable item in #options.
  3078. foreach (element_children($element) as $key) {
  3079. $row = array();
  3080. $row['data'] = array();
  3081. if (isset($element['#options'][$key]['#attributes'])) {
  3082. $row += $element['#options'][$key]['#attributes'];
  3083. }
  3084. // Render the checkbox / radio element.
  3085. $row['data'][] = drupal_render($element[$key]);
  3086. // As theme_table only maps header and row columns by order, create the
  3087. // correct order by iterating over the header fields.
  3088. foreach ($element['#header'] as $fieldname => $title) {
  3089. $row['data'][] = $element['#options'][$key][$fieldname];
  3090. }
  3091. $rows[] = $row;
  3092. }
  3093. // Add an empty header or a "Select all" checkbox to provide room for the
  3094. // checkboxes/radios in the first table column.
  3095. if ($element['#js_select']) {
  3096. // Add a "Select all" checkbox.
  3097. drupal_add_js('misc/tableselect.js');
  3098. array_unshift($header, array('class' => array('select-all')));
  3099. }
  3100. else {
  3101. // Add an empty header when radio buttons are displayed or a "Select all"
  3102. // checkbox is not desired.
  3103. array_unshift($header, '');
  3104. }
  3105. }
  3106. return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes']));
  3107. }
  3108. /**
  3109. * Creates checkbox or radio elements to populate a tableselect table.
  3110. *
  3111. * @param $element
  3112. * An associative array containing the properties and children of the
  3113. * tableselect element.
  3114. *
  3115. * @return
  3116. * The processed element.
  3117. */
  3118. function form_process_tableselect($element) {
  3119. if ($element['#multiple']) {
  3120. $value = is_array($element['#value']) ? $element['#value'] : array();
  3121. }
  3122. else {
  3123. // Advanced selection behavior makes no sense for radios.
  3124. $element['#js_select'] = FALSE;
  3125. }
  3126. $element['#tree'] = TRUE;
  3127. if (count($element['#options']) > 0) {
  3128. if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
  3129. $element['#default_value'] = array();
  3130. }
  3131. // Create a checkbox or radio for each item in #options in such a way that
  3132. // the value of the tableselect element behaves as if it had been of type
  3133. // checkboxes or radios.
  3134. foreach ($element['#options'] as $key => $choice) {
  3135. // Do not overwrite manually created children.
  3136. if (!isset($element[$key])) {
  3137. if ($element['#multiple']) {
  3138. $title = '';
  3139. if (!empty($element['#options'][$key]['title']['data']['#title'])) {
  3140. $title = t('Update @title', array(
  3141. '@title' => $element['#options'][$key]['title']['data']['#title'],
  3142. ));
  3143. }
  3144. $element[$key] = array(
  3145. '#type' => 'checkbox',
  3146. '#title' => $title,
  3147. '#title_display' => 'invisible',
  3148. '#return_value' => $key,
  3149. '#default_value' => isset($value[$key]) ? $key : NULL,
  3150. '#attributes' => $element['#attributes'],
  3151. );
  3152. }
  3153. else {
  3154. // Generate the parents as the autogenerator does, so we will have a
  3155. // unique id for each radio button.
  3156. $parents_for_id = array_merge($element['#parents'], array($key));
  3157. $element[$key] = array(
  3158. '#type' => 'radio',
  3159. '#title' => '',
  3160. '#return_value' => $key,
  3161. '#default_value' => ($element['#default_value'] == $key) ? $key : NULL,
  3162. '#attributes' => $element['#attributes'],
  3163. '#parents' => $element['#parents'],
  3164. '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
  3165. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  3166. );
  3167. }
  3168. if (isset($element['#options'][$key]['#weight'])) {
  3169. $element[$key]['#weight'] = $element['#options'][$key]['#weight'];
  3170. }
  3171. }
  3172. }
  3173. }
  3174. else {
  3175. $element['#value'] = array();
  3176. }
  3177. return $element;
  3178. }
  3179. /**
  3180. * Processes a machine-readable name form element.
  3181. *
  3182. * @param $element
  3183. * The form element to process. Properties used:
  3184. * - #machine_name: An associative array containing:
  3185. * - exists: A function name to invoke for checking whether a submitted
  3186. * machine name value already exists. The submitted value is passed as
  3187. * argument. In most cases, an existing API or menu argument loader
  3188. * function can be re-used. The callback is only invoked, if the submitted
  3189. * value differs from the element's #default_value.
  3190. * - source: (optional) The #array_parents of the form element containing
  3191. * the human-readable name (i.e., as contained in the $form structure) to
  3192. * use as source for the machine name. Defaults to array('name').
  3193. * - label: (optional) A text to display as label for the machine name value
  3194. * after the human-readable name form element. Defaults to "Machine name".
  3195. * - replace_pattern: (optional) A regular expression (without delimiters)
  3196. * matching disallowed characters in the machine name. Defaults to
  3197. * '[^a-z0-9_]+'.
  3198. * - replace: (optional) A character to replace disallowed characters in the
  3199. * machine name via JavaScript. Defaults to '_' (underscore). When using a
  3200. * different character, 'replace_pattern' needs to be set accordingly.
  3201. * - error: (optional) A custom form error message string to show, if the
  3202. * machine name contains disallowed characters.
  3203. * - standalone: (optional) Whether the live preview should stay in its own
  3204. * form element rather than in the suffix of the source element. Defaults
  3205. * to FALSE.
  3206. * - #maxlength: (optional) Should be set to the maximum allowed length of the
  3207. * machine name. Defaults to 64.
  3208. * - #disabled: (optional) Should be set to TRUE in case an existing machine
  3209. * name must not be changed after initial creation.
  3210. */
  3211. function form_process_machine_name($element, &$form_state) {
  3212. // Apply default form element properties.
  3213. $element += array(
  3214. '#title' => t('Machine-readable name'),
  3215. '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
  3216. '#machine_name' => array(),
  3217. '#field_prefix' => '',
  3218. '#field_suffix' => '',
  3219. '#suffix' => '',
  3220. );
  3221. // A form element that only wants to set one #machine_name property (usually
  3222. // 'source' only) would leave all other properties undefined, if the defaults
  3223. // were defined in hook_element_info(). Therefore, we apply the defaults here.
  3224. $element['#machine_name'] += array(
  3225. 'source' => array('name'),
  3226. 'target' => '#' . $element['#id'],
  3227. 'label' => t('Machine name'),
  3228. 'replace_pattern' => '[^a-z0-9_]+',
  3229. 'replace' => '_',
  3230. 'standalone' => FALSE,
  3231. 'field_prefix' => $element['#field_prefix'],
  3232. 'field_suffix' => $element['#field_suffix'],
  3233. );
  3234. // By default, machine names are restricted to Latin alphanumeric characters.
  3235. // So, default to LTR directionality.
  3236. if (!isset($element['#attributes'])) {
  3237. $element['#attributes'] = array();
  3238. }
  3239. $element['#attributes'] += array('dir' => 'ltr');
  3240. // The source element defaults to array('name'), but may have been overidden.
  3241. if (empty($element['#machine_name']['source'])) {
  3242. return $element;
  3243. }
  3244. // Retrieve the form element containing the human-readable name from the
  3245. // complete form in $form_state. By reference, because we may need to append
  3246. // a #field_suffix that will hold the live preview.
  3247. $key_exists = NULL;
  3248. $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);
  3249. if (!$key_exists) {
  3250. return $element;
  3251. }
  3252. $suffix_id = $source['#id'] . '-machine-name-suffix';
  3253. $element['#machine_name']['suffix'] = '#' . $suffix_id;
  3254. if ($element['#machine_name']['standalone']) {
  3255. $element['#suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
  3256. }
  3257. else {
  3258. // Append a field suffix to the source form element, which will contain
  3259. // the live preview of the machine name.
  3260. $source += array('#field_suffix' => '');
  3261. $source['#field_suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
  3262. $parents = array_merge($element['#machine_name']['source'], array('#field_suffix'));
  3263. drupal_array_set_nested_value($form_state['complete form'], $parents, $source['#field_suffix']);
  3264. }
  3265. $js_settings = array(
  3266. 'type' => 'setting',
  3267. 'data' => array(
  3268. 'machineName' => array(
  3269. '#' . $source['#id'] => $element['#machine_name'],
  3270. ),
  3271. ),
  3272. );
  3273. $element['#attached']['js'][] = 'misc/machine-name.js';
  3274. $element['#attached']['js'][] = $js_settings;
  3275. return $element;
  3276. }
  3277. /**
  3278. * Form element validation handler for machine_name elements.
  3279. *
  3280. * Note that #maxlength is validated by _form_validate() already.
  3281. */
  3282. function form_validate_machine_name(&$element, &$form_state) {
  3283. // Verify that the machine name not only consists of replacement tokens.
  3284. if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
  3285. form_error($element, t('The machine-readable name must contain unique characters.'));
  3286. }
  3287. // Verify that the machine name contains no disallowed characters.
  3288. if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
  3289. if (!isset($element['#machine_name']['error'])) {
  3290. // Since a hyphen is the most common alternative replacement character,
  3291. // a corresponding validation error message is supported here.
  3292. if ($element['#machine_name']['replace'] == '-') {
  3293. form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
  3294. }
  3295. // Otherwise, we assume the default (underscore).
  3296. else {
  3297. form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
  3298. }
  3299. }
  3300. else {
  3301. form_error($element, $element['#machine_name']['error']);
  3302. }
  3303. }
  3304. // Verify that the machine name is unique.
  3305. if ($element['#default_value'] !== $element['#value']) {
  3306. $function = $element['#machine_name']['exists'];
  3307. if ($function($element['#value'], $element, $form_state)) {
  3308. form_error($element, t('The machine-readable name is already in use. It must be unique.'));
  3309. }
  3310. }
  3311. }
  3312. /**
  3313. * Arranges fieldsets into groups.
  3314. *
  3315. * @param $element
  3316. * An associative array containing the properties and children of the
  3317. * fieldset. Note that $element must be taken by reference here, so processed
  3318. * child elements are taken over into $form_state.
  3319. * @param $form_state
  3320. * The $form_state array for the form this fieldset belongs to.
  3321. *
  3322. * @return
  3323. * The processed element.
  3324. */
  3325. function form_process_fieldset(&$element, &$form_state) {
  3326. $parents = implode('][', $element['#parents']);
  3327. // Each fieldset forms a new group. The #type 'vertical_tabs' basically only
  3328. // injects a new fieldset.
  3329. $form_state['groups'][$parents]['#group_exists'] = TRUE;
  3330. $element['#groups'] = &$form_state['groups'];
  3331. // Process vertical tabs group member fieldsets.
  3332. if (isset($element['#group'])) {
  3333. // Add this fieldset to the defined group (by reference).
  3334. $group = $element['#group'];
  3335. $form_state['groups'][$group][] = &$element;
  3336. }
  3337. // Contains form element summary functionalities.
  3338. $element['#attached']['library'][] = array('system', 'drupal.form');
  3339. // The .form-wrapper class is required for #states to treat fieldsets like
  3340. // containers.
  3341. if (!isset($element['#attributes']['class'])) {
  3342. $element['#attributes']['class'] = array();
  3343. }
  3344. // Collapsible fieldsets
  3345. if (!empty($element['#collapsible'])) {
  3346. $element['#attached']['library'][] = array('system', 'drupal.collapse');
  3347. $element['#attributes']['class'][] = 'collapsible';
  3348. if (!empty($element['#collapsed'])) {
  3349. $element['#attributes']['class'][] = 'collapsed';
  3350. }
  3351. }
  3352. return $element;
  3353. }
  3354. /**
  3355. * Adds members of this group as actual elements for rendering.
  3356. *
  3357. * @param $element
  3358. * An associative array containing the properties and children of the
  3359. * fieldset.
  3360. *
  3361. * @return
  3362. * The modified element with all group members.
  3363. */
  3364. function form_pre_render_fieldset($element) {
  3365. // Fieldsets may be rendered outside of a Form API context.
  3366. if (!isset($element['#parents']) || !isset($element['#groups'])) {
  3367. return $element;
  3368. }
  3369. // Inject group member elements belonging to this group.
  3370. $parents = implode('][', $element['#parents']);
  3371. $children = element_children($element['#groups'][$parents]);
  3372. if (!empty($children)) {
  3373. foreach ($children as $key) {
  3374. // Break references and indicate that the element should be rendered as
  3375. // group member.
  3376. $child = (array) $element['#groups'][$parents][$key];
  3377. $child['#group_fieldset'] = TRUE;
  3378. // Inject the element as new child element.
  3379. $element[] = $child;
  3380. $sort = TRUE;
  3381. }
  3382. // Re-sort the element's children if we injected group member elements.
  3383. if (isset($sort)) {
  3384. $element['#sorted'] = FALSE;
  3385. }
  3386. }
  3387. if (isset($element['#group'])) {
  3388. $group = $element['#group'];
  3389. // If this element belongs to a group, but the group-holding element does
  3390. // not exist, we need to render it (at its original location).
  3391. if (!isset($element['#groups'][$group]['#group_exists'])) {
  3392. // Intentionally empty to clarify the flow; we simply return $element.
  3393. }
  3394. // If we injected this element into the group, then we want to render it.
  3395. elseif (!empty($element['#group_fieldset'])) {
  3396. // Intentionally empty to clarify the flow; we simply return $element.
  3397. }
  3398. // Otherwise, this element belongs to a group and the group exists, so we do
  3399. // not render it.
  3400. elseif (element_children($element['#groups'][$group])) {
  3401. $element['#printed'] = TRUE;
  3402. }
  3403. }
  3404. return $element;
  3405. }
  3406. /**
  3407. * Creates a group formatted as vertical tabs.
  3408. *
  3409. * @param $element
  3410. * An associative array containing the properties and children of the
  3411. * fieldset.
  3412. * @param $form_state
  3413. * The $form_state array for the form this vertical tab widget belongs to.
  3414. *
  3415. * @return
  3416. * The processed element.
  3417. */
  3418. function form_process_vertical_tabs($element, &$form_state) {
  3419. // Inject a new fieldset as child, so that form_process_fieldset() processes
  3420. // this fieldset like any other fieldset.
  3421. $element['group'] = array(
  3422. '#type' => 'fieldset',
  3423. '#theme_wrappers' => array(),
  3424. '#parents' => $element['#parents'],
  3425. );
  3426. // The JavaScript stores the currently selected tab in this hidden
  3427. // field so that the active tab can be restored the next time the
  3428. // form is rendered, e.g. on preview pages or when form validation
  3429. // fails.
  3430. $name = implode('__', $element['#parents']);
  3431. if (isset($form_state['values'][$name . '__active_tab'])) {
  3432. $element['#default_tab'] = $form_state['values'][$name . '__active_tab'];
  3433. }
  3434. $element[$name . '__active_tab'] = array(
  3435. '#type' => 'hidden',
  3436. '#default_value' => $element['#default_tab'],
  3437. '#attributes' => array('class' => array('vertical-tabs-active-tab')),
  3438. );
  3439. return $element;
  3440. }
  3441. /**
  3442. * Returns HTML for an element's children fieldsets as vertical tabs.
  3443. *
  3444. * @param $variables
  3445. * An associative array containing:
  3446. * - element: An associative array containing the properties and children of
  3447. * the fieldset. Properties used: #children.
  3448. *
  3449. * @ingroup themeable
  3450. */
  3451. function theme_vertical_tabs($variables) {
  3452. $element = $variables['element'];
  3453. // Add required JavaScript and Stylesheet.
  3454. drupal_add_library('system', 'drupal.vertical-tabs');
  3455. $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
  3456. $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
  3457. return $output;
  3458. }
  3459. /**
  3460. * Returns HTML for a submit button form element.
  3461. *
  3462. * @param $variables
  3463. * An associative array containing:
  3464. * - element: An associative array containing the properties of the element.
  3465. * Properties used: #attributes, #button_type, #name, #value.
  3466. *
  3467. * @ingroup themeable
  3468. */
  3469. function theme_submit($variables) {
  3470. return theme('button', $variables['element']);
  3471. }
  3472. /**
  3473. * Returns HTML for a button form element.
  3474. *
  3475. * @param $variables
  3476. * An associative array containing:
  3477. * - element: An associative array containing the properties of the element.
  3478. * Properties used: #attributes, #button_type, #name, #value.
  3479. *
  3480. * @ingroup themeable
  3481. */
  3482. function theme_button($variables) {
  3483. $element = $variables['element'];
  3484. $element['#attributes']['type'] = 'submit';
  3485. element_set_attributes($element, array('id', 'name', 'value'));
  3486. $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  3487. if (!empty($element['#attributes']['disabled'])) {
  3488. $element['#attributes']['class'][] = 'form-button-disabled';
  3489. }
  3490. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3491. }
  3492. /**
  3493. * Returns HTML for an image button form element.
  3494. *
  3495. * @param $variables
  3496. * An associative array containing:
  3497. * - element: An associative array containing the properties of the element.
  3498. * Properties used: #attributes, #button_type, #name, #value, #title, #src.
  3499. *
  3500. * @ingroup themeable
  3501. */
  3502. function theme_image_button($variables) {
  3503. $element = $variables['element'];
  3504. $element['#attributes']['type'] = 'image';
  3505. element_set_attributes($element, array('id', 'name', 'value'));
  3506. $element['#attributes']['src'] = file_create_url($element['#src']);
  3507. if (!empty($element['#title'])) {
  3508. $element['#attributes']['alt'] = $element['#title'];
  3509. $element['#attributes']['title'] = $element['#title'];
  3510. }
  3511. $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  3512. if (!empty($element['#attributes']['disabled'])) {
  3513. $element['#attributes']['class'][] = 'form-button-disabled';
  3514. }
  3515. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3516. }
  3517. /**
  3518. * Returns HTML for a hidden form element.
  3519. *
  3520. * @param $variables
  3521. * An associative array containing:
  3522. * - element: An associative array containing the properties of the element.
  3523. * Properties used: #name, #value, #attributes.
  3524. *
  3525. * @ingroup themeable
  3526. */
  3527. function theme_hidden($variables) {
  3528. $element = $variables['element'];
  3529. $element['#attributes']['type'] = 'hidden';
  3530. element_set_attributes($element, array('name', 'value'));
  3531. return '<input' . drupal_attributes($element['#attributes']) . " />\n";
  3532. }
  3533. /**
  3534. * Returns HTML for a textfield form element.
  3535. *
  3536. * @param $variables
  3537. * An associative array containing:
  3538. * - element: An associative array containing the properties of the element.
  3539. * Properties used: #title, #value, #description, #size, #maxlength,
  3540. * #required, #attributes, #autocomplete_path.
  3541. *
  3542. * @ingroup themeable
  3543. */
  3544. function theme_textfield($variables) {
  3545. $element = $variables['element'];
  3546. $element['#attributes']['type'] = 'text';
  3547. element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  3548. _form_set_class($element, array('form-text'));
  3549. $extra = '';
  3550. if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
  3551. drupal_add_library('system', 'drupal.autocomplete');
  3552. $element['#attributes']['class'][] = 'form-autocomplete';
  3553. $attributes = array();
  3554. $attributes['type'] = 'hidden';
  3555. $attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
  3556. $attributes['value'] = url($element['#autocomplete_path'], array('absolute' => TRUE));
  3557. $attributes['disabled'] = 'disabled';
  3558. $attributes['class'][] = 'autocomplete';
  3559. $extra = '<input' . drupal_attributes($attributes) . ' />';
  3560. }
  3561. $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
  3562. return $output . $extra;
  3563. }
  3564. /**
  3565. * Returns HTML for a form.
  3566. *
  3567. * @param $variables
  3568. * An associative array containing:
  3569. * - element: An associative array containing the properties of the element.
  3570. * Properties used: #action, #method, #attributes, #children
  3571. *
  3572. * @ingroup themeable
  3573. */
  3574. function theme_form($variables) {
  3575. $element = $variables['element'];
  3576. if (isset($element['#action'])) {
  3577. $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  3578. }
  3579. element_set_attributes($element, array('method', 'id'));
  3580. if (empty($element['#attributes']['accept-charset'])) {
  3581. $element['#attributes']['accept-charset'] = "UTF-8";
  3582. }
  3583. // Anonymous DIV to satisfy XHTML compliance.
  3584. return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';
  3585. }
  3586. /**
  3587. * Returns HTML for a textarea form element.
  3588. *
  3589. * @param $variables
  3590. * An associative array containing:
  3591. * - element: An associative array containing the properties of the element.
  3592. * Properties used: #title, #value, #description, #rows, #cols, #required,
  3593. * #attributes
  3594. *
  3595. * @ingroup themeable
  3596. */
  3597. function theme_textarea($variables) {
  3598. $element = $variables['element'];
  3599. element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
  3600. _form_set_class($element, array('form-textarea'));
  3601. $wrapper_attributes = array(
  3602. 'class' => array('form-textarea-wrapper'),
  3603. );
  3604. // Add resizable behavior.
  3605. if (!empty($element['#resizable'])) {
  3606. drupal_add_library('system', 'drupal.textarea');
  3607. $wrapper_attributes['class'][] = 'resizable';
  3608. }
  3609. $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
  3610. $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
  3611. $output .= '</div>';
  3612. return $output;
  3613. }
  3614. /**
  3615. * Returns HTML for a password form element.
  3616. *
  3617. * @param $variables
  3618. * An associative array containing:
  3619. * - element: An associative array containing the properties of the element.
  3620. * Properties used: #title, #value, #description, #size, #maxlength,
  3621. * #required, #attributes.
  3622. *
  3623. * @ingroup themeable
  3624. */
  3625. function theme_password($variables) {
  3626. $element = $variables['element'];
  3627. $element['#attributes']['type'] = 'password';
  3628. element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
  3629. _form_set_class($element, array('form-text'));
  3630. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3631. }
  3632. /**
  3633. * Expands a weight element into a select element.
  3634. */
  3635. function form_process_weight($element) {
  3636. $element['#is_weight'] = TRUE;
  3637. // If the number of options is small enough, use a select field.
  3638. $max_elements = variable_get('drupal_weight_select_max', DRUPAL_WEIGHT_SELECT_MAX);
  3639. if ($element['#delta'] <= $max_elements) {
  3640. $element['#type'] = 'select';
  3641. for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
  3642. $weights[$n] = $n;
  3643. }
  3644. $element['#options'] = $weights;
  3645. $element += element_info('select');
  3646. }
  3647. // Otherwise, use a text field.
  3648. else {
  3649. $element['#type'] = 'textfield';
  3650. // Use a field big enough to fit most weights.
  3651. $element['#size'] = 10;
  3652. $element['#element_validate'] = array('element_validate_integer');
  3653. $element += element_info('textfield');
  3654. }
  3655. return $element;
  3656. }
  3657. /**
  3658. * Returns HTML for a file upload form element.
  3659. *
  3660. * For assistance with handling the uploaded file correctly, see the API
  3661. * provided by file.inc.
  3662. *
  3663. * @param $variables
  3664. * An associative array containing:
  3665. * - element: An associative array containing the properties of the element.
  3666. * Properties used: #title, #name, #size, #description, #required,
  3667. * #attributes.
  3668. *
  3669. * @ingroup themeable
  3670. */
  3671. function theme_file($variables) {
  3672. $element = $variables['element'];
  3673. $element['#attributes']['type'] = 'file';
  3674. element_set_attributes($element, array('id', 'name', 'size'));
  3675. _form_set_class($element, array('form-file'));
  3676. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3677. }
  3678. /**
  3679. * Returns HTML for a form element.
  3680. *
  3681. * Each form element is wrapped in a DIV container having the following CSS
  3682. * classes:
  3683. * - form-item: Generic for all form elements.
  3684. * - form-type-#type: The internal element #type.
  3685. * - form-item-#name: The internal form element #name (usually derived from the
  3686. * $form structure and set via form_builder()).
  3687. * - form-disabled: Only set if the form element is #disabled.
  3688. *
  3689. * In addition to the element itself, the DIV contains a label for the element
  3690. * based on the optional #title_display property, and an optional #description.
  3691. *
  3692. * The optional #title_display property can have these values:
  3693. * - before: The label is output before the element. This is the default.
  3694. * The label includes the #title and the required marker, if #required.
  3695. * - after: The label is output after the element. For example, this is used
  3696. * for radio and checkbox #type elements as set in system_element_info().
  3697. * If the #title is empty but the field is #required, the label will
  3698. * contain only the required marker.
  3699. * - invisible: Labels are critical for screen readers to enable them to
  3700. * properly navigate through forms but can be visually distracting. This
  3701. * property hides the label for everyone except screen readers.
  3702. * - attribute: Set the title attribute on the element to create a tooltip
  3703. * but output no label element. This is supported only for checkboxes
  3704. * and radios in form_pre_render_conditional_form_element(). It is used
  3705. * where a visual label is not needed, such as a table of checkboxes where
  3706. * the row and column provide the context. The tooltip will include the
  3707. * title and required marker.
  3708. *
  3709. * If the #title property is not set, then the label and any required marker
  3710. * will not be output, regardless of the #title_display or #required values.
  3711. * This can be useful in cases such as the password_confirm element, which
  3712. * creates children elements that have their own labels and required markers,
  3713. * but the parent element should have neither. Use this carefully because a
  3714. * field without an associated label can cause accessibility challenges.
  3715. *
  3716. * @param $variables
  3717. * An associative array containing:
  3718. * - element: An associative array containing the properties of the element.
  3719. * Properties used: #title, #title_display, #description, #id, #required,
  3720. * #children, #type, #name.
  3721. *
  3722. * @ingroup themeable
  3723. */
  3724. function theme_form_element($variables) {
  3725. $element = &$variables['element'];
  3726. // This is also used in the installer, pre-database setup.
  3727. $t = get_t();
  3728. // This function is invoked as theme wrapper, but the rendered form element
  3729. // may not necessarily have been processed by form_builder().
  3730. $element += array(
  3731. '#title_display' => 'before',
  3732. );
  3733. // Add element #id for #type 'item'.
  3734. if (isset($element['#markup']) && !empty($element['#id'])) {
  3735. $attributes['id'] = $element['#id'];
  3736. }
  3737. // Add element's #type and #name as class to aid with JS/CSS selectors.
  3738. $attributes['class'] = array('form-item');
  3739. if (!empty($element['#type'])) {
  3740. $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  3741. }
  3742. if (!empty($element['#name'])) {
  3743. $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  3744. }
  3745. // Add a class for disabled elements to facilitate cross-browser styling.
  3746. if (!empty($element['#attributes']['disabled'])) {
  3747. $attributes['class'][] = 'form-disabled';
  3748. }
  3749. $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
  3750. // If #title is not set, we don't display any label or required marker.
  3751. if (!isset($element['#title'])) {
  3752. $element['#title_display'] = 'none';
  3753. }
  3754. $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
  3755. $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
  3756. switch ($element['#title_display']) {
  3757. case 'before':
  3758. case 'invisible':
  3759. $output .= ' ' . theme('form_element_label', $variables);
  3760. $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  3761. break;
  3762. case 'after':
  3763. $output .= ' ' . $prefix . $element['#children'] . $suffix;
  3764. $output .= ' ' . theme('form_element_label', $variables) . "\n";
  3765. break;
  3766. case 'none':
  3767. case 'attribute':
  3768. // Output no label and no required marker, only the children.
  3769. $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  3770. break;
  3771. }
  3772. if (!empty($element['#description'])) {
  3773. $output .= '<div class="description">' . $element['#description'] . "</div>\n";
  3774. }
  3775. $output .= "</div>\n";
  3776. return $output;
  3777. }
  3778. /**
  3779. * Returns HTML for a marker for required form elements.
  3780. *
  3781. * @param $variables
  3782. * An associative array containing:
  3783. * - element: An associative array containing the properties of the element.
  3784. *
  3785. * @ingroup themeable
  3786. */
  3787. function theme_form_required_marker($variables) {
  3788. // This is also used in the installer, pre-database setup.
  3789. $t = get_t();
  3790. $attributes = array(
  3791. 'class' => 'form-required',
  3792. 'title' => $t('This field is required.'),
  3793. );
  3794. return '<span' . drupal_attributes($attributes) . '>*</span>';
  3795. }
  3796. /**
  3797. * Returns HTML for a form element label and required marker.
  3798. *
  3799. * Form element labels include the #title and a #required marker. The label is
  3800. * associated with the element itself by the element #id. Labels may appear
  3801. * before or after elements, depending on theme_form_element() and
  3802. * #title_display.
  3803. *
  3804. * This function will not be called for elements with no labels, depending on
  3805. * #title_display. For elements that have an empty #title and are not required,
  3806. * this function will output no label (''). For required elements that have an
  3807. * empty #title, this will output the required marker alone within the label.
  3808. * The label will use the #id to associate the marker with the field that is
  3809. * required. That is especially important for screenreader users to know
  3810. * which field is required.
  3811. *
  3812. * @param $variables
  3813. * An associative array containing:
  3814. * - element: An associative array containing the properties of the element.
  3815. * Properties used: #required, #title, #id, #value, #description.
  3816. *
  3817. * @ingroup themeable
  3818. */
  3819. function theme_form_element_label($variables) {
  3820. $element = $variables['element'];
  3821. // This is also used in the installer, pre-database setup.
  3822. $t = get_t();
  3823. // If title and required marker are both empty, output no label.
  3824. if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
  3825. return '';
  3826. }
  3827. // If the element is required, a required marker is appended to the label.
  3828. $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
  3829. $title = filter_xss_admin($element['#title']);
  3830. $attributes = array();
  3831. // Style the label as class option to display inline with the element.
  3832. if ($element['#title_display'] == 'after') {
  3833. $attributes['class'] = 'option';
  3834. }
  3835. // Show label only to screen readers to avoid disruption in visual flows.
  3836. elseif ($element['#title_display'] == 'invisible') {
  3837. $attributes['class'] = 'element-invisible';
  3838. }
  3839. if (!empty($element['#id'])) {
  3840. $attributes['for'] = $element['#id'];
  3841. }
  3842. // The leading whitespace helps visually separate fields from inline labels.
  3843. return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
  3844. }
  3845. /**
  3846. * Sets a form element's class attribute.
  3847. *
  3848. * Adds 'required' and 'error' classes as needed.
  3849. *
  3850. * @param $element
  3851. * The form element.
  3852. * @param $name
  3853. * Array of new class names to be added.
  3854. */
  3855. function _form_set_class(&$element, $class = array()) {
  3856. if (!empty($class)) {
  3857. if (!isset($element['#attributes']['class'])) {
  3858. $element['#attributes']['class'] = array();
  3859. }
  3860. $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
  3861. }
  3862. // This function is invoked from form element theme functions, but the
  3863. // rendered form element may not necessarily have been processed by
  3864. // form_builder().
  3865. if (!empty($element['#required'])) {
  3866. $element['#attributes']['class'][] = 'required';
  3867. }
  3868. if (isset($element['#parents']) && form_get_error($element)) {
  3869. $element['#attributes']['class'][] = 'error';
  3870. }
  3871. }
  3872. /**
  3873. * Form element validation handler for integer elements.
  3874. */
  3875. function element_validate_integer($element, &$form_state) {
  3876. $value = $element['#value'];
  3877. if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
  3878. form_error($element, t('%name must be an integer.', array('%name' => $element['#title'])));
  3879. }
  3880. }
  3881. /**
  3882. * Form element validation handler for integer elements that must be positive.
  3883. */
  3884. function element_validate_integer_positive($element, &$form_state) {
  3885. $value = $element['#value'];
  3886. if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
  3887. form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  3888. }
  3889. }
  3890. /**
  3891. * Form element validation handler for number elements.
  3892. */
  3893. function element_validate_number($element, &$form_state) {
  3894. $value = $element['#value'];
  3895. if ($value != '' && !is_numeric($value)) {
  3896. form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
  3897. }
  3898. }
  3899. /**
  3900. * @} End of "defgroup form_api".
  3901. */
  3902. /**
  3903. * @defgroup batch Batch operations
  3904. * @{
  3905. * Creates and processes batch operations.
  3906. *
  3907. * Functions allowing forms processing to be spread out over several page
  3908. * requests, thus ensuring that the processing does not get interrupted
  3909. * because of a PHP timeout, while allowing the user to receive feedback
  3910. * on the progress of the ongoing operations.
  3911. *
  3912. * The API is primarily designed to integrate nicely with the Form API
  3913. * workflow, but can also be used by non-Form API scripts (like update.php)
  3914. * or even simple page callbacks (which should probably be used sparingly).
  3915. *
  3916. * Example:
  3917. * @code
  3918. * $batch = array(
  3919. * 'title' => t('Exporting'),
  3920. * 'operations' => array(
  3921. * array('my_function_1', array($account->uid, 'story')),
  3922. * array('my_function_2', array()),
  3923. * ),
  3924. * 'finished' => 'my_finished_callback',
  3925. * 'file' => 'path_to_file_containing_myfunctions',
  3926. * );
  3927. * batch_set($batch);
  3928. * // Only needed if not inside a form _submit handler.
  3929. * // Setting redirect in batch_process.
  3930. * batch_process('node/1');
  3931. * @endcode
  3932. *
  3933. * Note: if the batch 'title', 'init_message', 'progress_message', or
  3934. * 'error_message' could contain any user input, it is the responsibility of
  3935. * the code calling batch_set() to sanitize them first with a function like
  3936. * check_plain() or filter_xss(). Furthermore, if the batch operation
  3937. * returns any user input in the 'results' or 'message' keys of $context,
  3938. * it must also sanitize them first.
  3939. *
  3940. * Sample batch operations:
  3941. * @code
  3942. * // Simple and artificial: load a node of a given type for a given user
  3943. * function my_function_1($uid, $type, &$context) {
  3944. * // The $context array gathers batch context information about the execution (read),
  3945. * // as well as 'return values' for the current operation (write)
  3946. * // The following keys are provided :
  3947. * // 'results' (read / write): The array of results gathered so far by
  3948. * // the batch processing, for the current operation to append its own.
  3949. * // 'message' (write): A text message displayed in the progress page.
  3950. * // The following keys allow for multi-step operations :
  3951. * // 'sandbox' (read / write): An array that can be freely used to
  3952. * // store persistent data between iterations. It is recommended to
  3953. * // use this instead of $_SESSION, which is unsafe if the user
  3954. * // continues browsing in a separate window while the batch is processing.
  3955. * // 'finished' (write): A float number between 0 and 1 informing
  3956. * // the processing engine of the completion level for the operation.
  3957. * // 1 (or no value explicitly set) means the operation is finished
  3958. * // and the batch processing can continue to the next operation.
  3959. *
  3960. * $node = node_load(array('uid' => $uid, 'type' => $type));
  3961. * $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  3962. * $context['message'] = check_plain($node->title);
  3963. * }
  3964. *
  3965. * // More advanced example: multi-step operation - load all nodes, five by five
  3966. * function my_function_2(&$context) {
  3967. * if (empty($context['sandbox'])) {
  3968. * $context['sandbox']['progress'] = 0;
  3969. * $context['sandbox']['current_node'] = 0;
  3970. * $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  3971. * }
  3972. * $limit = 5;
  3973. * $result = db_select('node')
  3974. * ->fields('node', array('nid'))
  3975. * ->condition('nid', $context['sandbox']['current_node'], '>')
  3976. * ->orderBy('nid')
  3977. * ->range(0, $limit)
  3978. * ->execute();
  3979. * foreach ($result as $row) {
  3980. * $node = node_load($row->nid, NULL, TRUE);
  3981. * $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  3982. * $context['sandbox']['progress']++;
  3983. * $context['sandbox']['current_node'] = $node->nid;
  3984. * $context['message'] = check_plain($node->title);
  3985. * }
  3986. * if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  3987. * $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  3988. * }
  3989. * }
  3990. * @endcode
  3991. *
  3992. * Sample 'finished' callback:
  3993. * @code
  3994. * function batch_test_finished($success, $results, $operations) {
  3995. * // The 'success' parameter means no fatal PHP errors were detected. All
  3996. * // other error management should be handled using 'results'.
  3997. * if ($success) {
  3998. * $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
  3999. * }
  4000. * else {
  4001. * $message = t('Finished with an error.');
  4002. * }
  4003. * drupal_set_message($message);
  4004. * // Providing data for the redirected page is done through $_SESSION.
  4005. * foreach ($results as $result) {
  4006. * $items[] = t('Loaded node %title.', array('%title' => $result));
  4007. * }
  4008. * $_SESSION['my_batch_results'] = $items;
  4009. * }
  4010. * @endcode
  4011. */
  4012. /**
  4013. * Adds a new batch.
  4014. *
  4015. * Batch operations are added as new batch sets. Batch sets are used to spread
  4016. * processing (primarily, but not exclusively, forms processing) over several
  4017. * page requests. This helps to ensure that the processing is not interrupted
  4018. * due to PHP timeouts, while users are still able to receive feedback on the
  4019. * progress of the ongoing operations. Combining related operations into
  4020. * distinct batch sets provides clean code independence for each batch set,
  4021. * ensuring that two or more batches, submitted independently, can be processed
  4022. * without mutual interference. Each batch set may specify its own set of
  4023. * operations and results, produce its own UI messages, and trigger its own
  4024. * 'finished' callback. Batch sets are processed sequentially, with the progress
  4025. * bar starting afresh for each new set.
  4026. *
  4027. * @param $batch_definition
  4028. * An associative array defining the batch, with the following elements (all
  4029. * are optional except as noted):
  4030. * - operations: (required) Array of function calls to be performed.
  4031. * Example:
  4032. * @code
  4033. * array(
  4034. * array('my_function_1', array($arg1)),
  4035. * array('my_function_2', array($arg2_1, $arg2_2)),
  4036. * )
  4037. * @endcode
  4038. * - title: A safe, translated string to use as the title for the progress
  4039. * page. Defaults to t('Processing').
  4040. * - init_message: Message displayed while the processing is initialized.
  4041. * Defaults to t('Initializing.').
  4042. * - progress_message: Message displayed while processing the batch. Available
  4043. * placeholders are @current, @remaining, @total, @percentage, @estimate and
  4044. * @elapsed. Defaults to t('Completed @current of @total.').
  4045. * - error_message: Message displayed if an error occurred while processing
  4046. * the batch. Defaults to t('An error has occurred.').
  4047. * - finished: Name of a function to be executed after the batch has
  4048. * completed. This should be used to perform any result massaging that may
  4049. * be needed, and possibly save data in $_SESSION for display after final
  4050. * page redirection.
  4051. * - file: Path to the file containing the definitions of the 'operations' and
  4052. * 'finished' functions, for instance if they don't reside in the main
  4053. * .module file. The path should be relative to base_path(), and thus should
  4054. * be built using drupal_get_path().
  4055. * - css: Array of paths to CSS files to be used on the progress page.
  4056. * - url_options: options passed to url() when constructing redirect URLs for
  4057. * the batch.
  4058. */
  4059. function batch_set($batch_definition) {
  4060. if ($batch_definition) {
  4061. $batch =& batch_get();
  4062. // Initialize the batch if needed.
  4063. if (empty($batch)) {
  4064. $batch = array(
  4065. 'sets' => array(),
  4066. 'has_form_submits' => FALSE,
  4067. );
  4068. }
  4069. // Base and default properties for the batch set.
  4070. // Use get_t() to allow batches at install time.
  4071. $t = get_t();
  4072. $init = array(
  4073. 'sandbox' => array(),
  4074. 'results' => array(),
  4075. 'success' => FALSE,
  4076. 'start' => 0,
  4077. 'elapsed' => 0,
  4078. );
  4079. $defaults = array(
  4080. 'title' => $t('Processing'),
  4081. 'init_message' => $t('Initializing.'),
  4082. 'progress_message' => $t('Completed @current of @total.'),
  4083. 'error_message' => $t('An error has occurred.'),
  4084. 'css' => array(),
  4085. );
  4086. $batch_set = $init + $batch_definition + $defaults;
  4087. // Tweak init_message to avoid the bottom of the page flickering down after
  4088. // init phase.
  4089. $batch_set['init_message'] .= '<br/>&nbsp;';
  4090. // The non-concurrent workflow of batch execution allows us to save
  4091. // numberOfItems() queries by handling our own counter.
  4092. $batch_set['total'] = count($batch_set['operations']);
  4093. $batch_set['count'] = $batch_set['total'];
  4094. // Add the set to the batch.
  4095. if (empty($batch['id'])) {
  4096. // The batch is not running yet. Simply add the new set.
  4097. $batch['sets'][] = $batch_set;
  4098. }
  4099. else {
  4100. // The set is being added while the batch is running. Insert the new set
  4101. // right after the current one to ensure execution order, and store its
  4102. // operations in a queue.
  4103. $index = $batch['current_set'] + 1;
  4104. $slice1 = array_slice($batch['sets'], 0, $index);
  4105. $slice2 = array_slice($batch['sets'], $index);
  4106. $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
  4107. _batch_populate_queue($batch, $index);
  4108. }
  4109. }
  4110. }
  4111. /**
  4112. * Processes the batch.
  4113. *
  4114. * Unless the batch has been marked with 'progressive' = FALSE, the function
  4115. * issues a drupal_goto and thus ends page execution.
  4116. *
  4117. * This function is generally not needed in form submit handlers;
  4118. * Form API takes care of batches that were set during form submission.
  4119. *
  4120. * @param $redirect
  4121. * (optional) Path to redirect to when the batch has finished processing.
  4122. * @param $url
  4123. * (optional - should only be used for separate scripts like update.php)
  4124. * URL of the batch processing page.
  4125. * @param $redirect_callback
  4126. * (optional) Specify a function to be called to redirect to the progressive
  4127. * processing page. By default drupal_goto() will be used to redirect to a
  4128. * page which will do the progressive page. Specifying another function will
  4129. * allow the progressive processing to be processed differently.
  4130. */
  4131. function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = 'drupal_goto') {
  4132. $batch =& batch_get();
  4133. drupal_theme_initialize();
  4134. if (isset($batch)) {
  4135. // Add process information
  4136. $process_info = array(
  4137. 'current_set' => 0,
  4138. 'progressive' => TRUE,
  4139. 'url' => $url,
  4140. 'url_options' => array(),
  4141. 'source_url' => $_GET['q'],
  4142. 'redirect' => $redirect,
  4143. 'theme' => $GLOBALS['theme_key'],
  4144. 'redirect_callback' => $redirect_callback,
  4145. );
  4146. $batch += $process_info;
  4147. // The batch is now completely built. Allow other modules to make changes
  4148. // to the batch so that it is easier to reuse batch processes in other
  4149. // environments.
  4150. drupal_alter('batch', $batch);
  4151. // Assign an arbitrary id: don't rely on a serial column in the 'batch'
  4152. // table, since non-progressive batches skip database storage completely.
  4153. $batch['id'] = db_next_id();
  4154. // Move operations to a job queue. Non-progressive batches will use a
  4155. // memory-based queue.
  4156. foreach ($batch['sets'] as $key => $batch_set) {
  4157. _batch_populate_queue($batch, $key);
  4158. }
  4159. // Initiate processing.
  4160. if ($batch['progressive']) {
  4161. // Now that we have a batch id, we can generate the redirection link in
  4162. // the generic error message.
  4163. $t = get_t();
  4164. $batch['error_message'] = $t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => url($url, array('query' => array('id' => $batch['id'], 'op' => 'finished')))));
  4165. // Clear the way for the drupal_goto() redirection to the batch processing
  4166. // page, by saving and unsetting the 'destination', if there is any.
  4167. if (isset($_GET['destination'])) {
  4168. $batch['destination'] = $_GET['destination'];
  4169. unset($_GET['destination']);
  4170. }
  4171. // Store the batch.
  4172. db_insert('batch')
  4173. ->fields(array(
  4174. 'bid' => $batch['id'],
  4175. 'timestamp' => REQUEST_TIME,
  4176. 'token' => drupal_get_token($batch['id']),
  4177. 'batch' => serialize($batch),
  4178. ))
  4179. ->execute();
  4180. // Set the batch number in the session to guarantee that it will stay alive.
  4181. $_SESSION['batches'][$batch['id']] = TRUE;
  4182. // Redirect for processing.
  4183. $function = $batch['redirect_callback'];
  4184. if (function_exists($function)) {
  4185. $function($batch['url'], array('query' => array('op' => 'start', 'id' => $batch['id'])));
  4186. }
  4187. }
  4188. else {
  4189. // Non-progressive execution: bypass the whole progressbar workflow
  4190. // and execute the batch in one pass.
  4191. require_once DRUPAL_ROOT . '/includes/batch.inc';
  4192. _batch_process();
  4193. }
  4194. }
  4195. }
  4196. /**
  4197. * Retrieves the current batch.
  4198. */
  4199. function &batch_get() {
  4200. // Not drupal_static(), because Batch API operates at a lower level than most
  4201. // use-cases for resetting static variables, and we specifically do not want a
  4202. // global drupal_static_reset() resetting the batch information. Functions
  4203. // that are part of the Batch API and need to reset the batch information may
  4204. // call batch_get() and manipulate the result by reference. Functions that are
  4205. // not part of the Batch API can also do this, but shouldn't.
  4206. static $batch = array();
  4207. return $batch;
  4208. }
  4209. /**
  4210. * Populates a job queue with the operations of a batch set.
  4211. *
  4212. * Depending on whether the batch is progressive or not, the BatchQueue or
  4213. * BatchMemoryQueue handler classes will be used.
  4214. *
  4215. * @param $batch
  4216. * The batch array.
  4217. * @param $set_id
  4218. * The id of the set to process.
  4219. *
  4220. * @return
  4221. * The name and class of the queue are added by reference to the batch set.
  4222. */
  4223. function _batch_populate_queue(&$batch, $set_id) {
  4224. $batch_set = &$batch['sets'][$set_id];
  4225. if (isset($batch_set['operations'])) {
  4226. $batch_set += array(
  4227. 'queue' => array(
  4228. 'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
  4229. 'class' => $batch['progressive'] ? 'BatchQueue' : 'BatchMemoryQueue',
  4230. ),
  4231. );
  4232. $queue = _batch_queue($batch_set);
  4233. $queue->createQueue();
  4234. foreach ($batch_set['operations'] as $operation) {
  4235. $queue->createItem($operation);
  4236. }
  4237. unset($batch_set['operations']);
  4238. }
  4239. }
  4240. /**
  4241. * Returns a queue object for a batch set.
  4242. *
  4243. * @param $batch_set
  4244. * The batch set.
  4245. *
  4246. * @return
  4247. * The queue object.
  4248. */
  4249. function _batch_queue($batch_set) {
  4250. static $queues;
  4251. // The class autoloader is not available when running update.php, so make
  4252. // sure the files are manually included.
  4253. if (!isset($queues)) {
  4254. $queues = array();
  4255. require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
  4256. require_once DRUPAL_ROOT . '/includes/batch.queue.inc';
  4257. }
  4258. if (isset($batch_set['queue'])) {
  4259. $name = $batch_set['queue']['name'];
  4260. $class = $batch_set['queue']['class'];
  4261. if (!isset($queues[$class][$name])) {
  4262. $queues[$class][$name] = new $class($name);
  4263. }
  4264. return $queues[$class][$name];
  4265. }
  4266. }
  4267. /**
  4268. * @} End of "defgroup batch".
  4269. */
Login or register to post comments