Skip navigation
Help

form.inc

  1. drupal
    1. 6 drupal/includes/form.inc
    2. 7 drupal/includes/form.inc

Functions & methods

NameDescription
batch_getRetrieves the current batch.
batch_processProcesses the batch.
batch_setOpens a new batch.
date_validateValidates the date type to stop dates like February 30, 2006.
drupal_build_formBuild and process a form based on a form id.
drupal_form_submitRetrieves, populates, and processes a form.
drupal_get_formWrapper for drupal_build_form() for use when $form_state is not needed.
drupal_prepare_formPrepares a structured form array by adding required elements, executing any hook_form_alter functions, and optionally inserting a validation token to prevent tampering.
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 from the $form_state using the validate functions defined in a structured form array.
element_validate_integerHelper form element validator: integer.
element_validate_integer_positiveHelper form element validator: integer > 0.
element_validate_numberHelper form element validator: number.
form_builderWalk through the structured form array, adding any required properties to each element and mapping the incoming input data to the proper elements. Also, execute any #process handlers attached to a specific element.
form_clear_errorClear all errors against all form elements made by form_set_error().
form_errorFlag an element as having an error.
form_execute_handlersA helper function used to execute custom validation and submission handlers for a given form. Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.
form_get_cacheFetch a form from cache.
form_get_errorReturns the error message filed against the given form element.
form_get_errorsReturn an associative array of all errors.
form_get_optionsTraverses a select element's #option array looking for any values that hold the given key. Returns an array of indexes that match.
form_load_includeLoads an include file and makes sure it is 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_elementAdd form_element theming to an element if title or description is set.
form_pre_render_fieldsetAdds members of this group as actual elements for rendering.
form_process_actionsProcesses a form actions container element.
form_process_checkboxSets the #checked property of a checkbox element.
form_process_checkboxes
form_process_containerProcesses a container element.
form_process_dateRoll out a single date element.
form_process_fieldsetAdds fieldsets to the specified group or adds group members to this fieldset.
form_process_machine_nameProcesses a machine-readable name form element.
form_process_password_confirmExpand a password_confirm field into two text boxes.
form_process_radiosRoll out a single radios element to a list of radios, using the options array as index.
form_process_selectProcesses a select list form element.
form_process_tableselectCreate the correct amount of checkbox or radio elements to populate the table.
form_process_vertical_tabsCreates a group formatted as vertical tabs.
form_process_weightExpand weight elements into selects.
form_select_optionsConverts a select form element's options array into an HTML.
form_set_cacheStore a form in the cache.
form_set_errorFiles an error against a form element.
form_set_valueChange submitted form values during form validation.
form_state_defaultsRetrieve 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_valueHelper function to determine the value for a checkboxes form element.
form_type_checkbox_valueHelper function to determine the value for a checkbox form element.
form_type_image_button_valueHelper function to determine the value for an image button form element.
form_type_password_confirm_valueHelper function to determine the value for a password_confirm form element.
form_type_select_valueHelper function to determine the value for a select form element.
form_type_tableselect_valueHelper function to determine the value for a tableselect form element.
form_type_textfield_valueHelper function to determine the value for a textfield form element.
form_type_token_valueHelper function to determine the value for form's token value.
form_validate_machine_nameForm element validation handler for #type 'machine_name'.
map_monthHelper function for usage with drupal_map_assoc to display month names.
password_confirm_validateValidate password_confirm element.
theme_buttonReturns HTML for a button form element.
theme_checkboxReturns HTML for a checkbox form element.
theme_checkboxesReturns HTML for a set of checkbox form elements.
theme_containerReturns HTML to wrap child elements in a container.
theme_dateReturns HTML for a date selection form element.
theme_fieldsetReturns HTML for a fieldset form element and its children.
theme_fileReturns HTML for a file upload form element.
theme_formReturns HTML for a form.
theme_form_elementReturns HTML for a form element.
theme_form_element_labelReturns HTML for a form element label and required marker.
theme_form_required_markerReturns HTML for a marker for required form elements.
theme_hiddenReturns HTML for a hidden form element.
theme_image_buttonReturns HTML for an image button form element.
theme_passwordReturns HTML for a password form element.
theme_radioReturns HTML for a radio button form element.
theme_radiosReturns HTML for a set of radio button form elements.
theme_selectReturns HTML for a select form element.
theme_submitReturns HTML for a submit button form element.
theme_tableselectReturns HTML for a table with radio buttons or checkboxes.
theme_textareaReturns HTML for a textarea form element.
theme_textfieldReturns HTML for a textfield form element.
theme_vertical_tabsReturns HTML for an element's children fieldsets as vertical tabs.
weight_valueIf no default value is set for weight select boxes, use 0.
_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_elementPopulate the #value and #name properties of input elements so they can be processed and rendered.
_form_button_was_clickedHelper function to handle the convoluted logic of button click detection.
_form_element_triggered_scripted_submissionHelper function to handle the convoluted logic of button click detection.
_form_options_flattenHelper function for form_options_flatten().
_form_set_classSets a form element's class attribute.
_form_validatePerforms validation on form elements. First ensures required fields are completed, #maxlength is not exceeded, and selected options were in the list of options given to the user. Then calls user-defined validators.

File

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