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