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 processes a form for a given 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.
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 the 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_autocompleteAdds autocomplete functionality to elements with a valid #autocomplete_path.
form_process_buttonProcesses a form button 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_pattern#process callback for #pattern form element property.
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_range_valueDetermines the value for a range 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_emailForm element validation handler for #type 'email'.
form_validate_machine_nameForm element validation handler for machine_name elements.
form_validate_numberForm element validation handler for #type 'number'.
form_validate_pattern#element_validate callback for #pattern form element property.
form_validate_urlForm element validation handler for #type 'url'.
map_monthRenders a month name for display.
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_emailReturns HTML for an email 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_numberReturns HTML for a number 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_rangeReturns HTML for a range form element.
theme_searchReturns HTML for a search form element.
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_telReturns HTML for a tel form element.
theme_textareaReturns HTML for a textarea form element.
theme_textfieldReturns HTML for a textfield form element.
theme_urlReturns HTML for a url 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

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