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