form.inc

Functions for form and batch generation and processing.

Archivo

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

Functions

Nombreorden descendente Descripción
batch_get Retrieves the current batch.
batch_process Processes the batch.
batch_set Adds a new batch.
date_validate Validates the date type to prevent invalid dates (e.g., February 30, 2006).
drupal_build_form Builds and process a form based on a form id.
drupal_form_submit Retrieves, populates, and processes a form.
drupal_get_form Returns a renderable form array for a given form ID.
drupal_prepare_form Prepares a structured form array.
drupal_process_form Processes a form submission.
drupal_rebuild_form Constructs a new $form from the information in $form_state.
drupal_redirect_form Redirects the user to a URL after a form has been processed.
drupal_retrieve_form Retrieves the structured array that defines a given form.
drupal_validate_form Validates user-submitted form data in the $form_state array.
element_validate_integer Form element validation handler for integer elements.
element_validate_integer_positive Form element validation handler for integer elements that must be positive.
element_validate_number Form element validation handler for number elements.
form_builder Builds and processes all elements in the structured form array.
form_clear_error Clears all errors against all form elements made by form_set_error().
form_error Flags an element as having an error.
form_execute_handlers Executes custom validation and submission handlers for a given form.
form_get_cache Fetches a form from cache.
form_get_error Returns the error message filed against the given form element.
form_get_errors Returns an associative array of all errors.
form_get_options Returns the indexes of a select element's options matching a given key.
form_load_include Ensures an include file is loaded whenever the form is processed.
form_options_flatten Allows PHP array processing of multiple select options with the same value.
form_pre_render_conditional_form_element Adds form element theming to an element if its title or description is set.
form_pre_render_fieldset Adds members of this group as actual elements for rendering.
form_process_actions Processes a form actions container element.
form_process_checkbox Sets the #checked property of a checkbox element.
form_process_checkboxes Processes a checkboxes form element.
form_process_container Processes a container element.
form_process_date Expands a date element into year, month, and day select elements.
form_process_fieldset Arranges fieldsets into groups.
form_process_machine_name Processes a machine-readable name form element.
form_process_password_confirm Expand a password_confirm field into two text boxes.
form_process_radios Expands a radios element into individual radio elements.
form_process_select Processes a select list form element.
form_process_tableselect Creates checkbox or radio elements to populate a tableselect table.
form_process_vertical_tabs Creates a group formatted as vertical tabs.
form_process_weight Expands a weight element into a select element.
form_select_options Converts a select form element's options array into HTML.
form_set_cache Stores a form in the cache.
form_set_error Files an error against a form element.
form_set_value Changes submitted form values during form validation.
form_state_defaults Retrieves default values for the $form_state array.
form_state_keys_no_cache Returns an array of $form_state keys that shouldn't be cached.
form_state_values_clean Removes internal Form API elements and buttons from submitted form values.
form_type_checkboxes_value Determines the value for a checkboxes form element.
form_type_checkbox_value Determines the value for a checkbox form element.
form_type_image_button_value Determines the value for an image button form element.
form_type_password_confirm_value Determines the value for a password_confirm form element.
form_type_radios_value Form value callback: Determines the value for a #type radios form element.
form_type_select_value Determines the value for a select form element.
form_type_tableselect_value Determines the value for a tableselect form element.
form_type_textfield_value Determines the value for a textfield form element.
form_type_token_value Determines the value for form's token value.
form_validate_machine_name Form element validation handler for machine_name elements.
map_month Helper function for usage with drupal_map_assoc to display month names.
password_confirm_validate Validates a password_confirm element.
theme_button Returns HTML for a button form element.
theme_checkbox Returns HTML for a checkbox form element.
theme_checkboxes Returns HTML for a set of checkbox form elements.
theme_container Returns HTML to wrap child elements in a container.
theme_date Returns HTML for a date selection form element.
theme_fieldset Returns HTML for a fieldset form element and its children.
theme_file Returns HTML for a file upload form element.
theme_form Returns HTML for a form.
theme_form_element Returns HTML for a form element.
theme_form_element_label Returns HTML for a form element label and required marker.
theme_form_required_marker Returns HTML for a marker for required form elements.
theme_hidden Returns HTML for a hidden form element.
theme_image_button Returns HTML for an image button form element.
theme_password Returns HTML for a password form element.
theme_radio Returns HTML for a radio button form element.
theme_radios Returns HTML for a set of radio button form elements.
theme_select Returns HTML for a select form element.
theme_submit Returns HTML for a submit button form element.
theme_tableselect Returns HTML for a table with radio buttons or checkboxes.
theme_textarea Returns HTML for a textarea form element.
theme_textfield Returns HTML for a textfield form element.
theme_vertical_tabs Returns HTML for an element's children fieldsets as vertical tabs.
weight_value Sets the value for a weight element, with zero as a default.
_batch_populate_queue Populates a job queue with the operations of a batch set.
_batch_queue Returns a queue object for a batch set.
_form_builder_handle_input_element Adds the #name and #value properties of an input element before rendering.
_form_button_was_clicked Determines if a given button triggered the form submission.
_form_element_triggered_scripted_submission Detects if an element triggered the form submission via Ajax.
_form_options_flatten Iterates over an array and returns a flat array with duplicate keys removed.
_form_set_class Sets a form element's class attribute.
_form_validate Performs validation on form elements.