form.inc 122 KB
Newer Older
1
<?php
2

3
4
5
6
7
/**
 * @file
 * Functions for form and batch generation and processing.
 */

8
use Drupal\Component\Utility\NestedArray;
9
use Drupal\Component\Utility\Number;
10
use Drupal\Component\Utility\String;
11
use Drupal\Component\Utility\UrlHelper;
12
use Drupal\Component\Utility\Xss;
13
use Drupal\Core\Database\Database;
14
use Drupal\Core\Language\Language;
15
use Drupal\Core\Template\Attribute;
16
use Drupal\Core\Utility\Color;
17
use Symfony\Component\HttpFoundation\RedirectResponse;
18

19
/**
20
21
22
23
24
25
 * @defgroup forms Form builder functions
 * @{
 * Functions that build an abstract representation of a HTML form.
 *
 * All modules should declare their form builder functions to be in this
 * group and each builder function should reference its validate and submit
26
 * functions using \@see. Conversely, validate and submit functions should
27
 * reference the form builder function using \@see. For examples, of this see
28
 * system_modules_uninstall() or user_pass(), the latter of which has the
29
 * following in its doxygen documentation:
30
31
32
 * - \@ingroup forms
 * - \@see user_pass_validate()
 * - \@see user_pass_submit()
33
 *
34
 * @}
35
36
37
38
 */

/**
 * @defgroup form_api Form generation
39
 * @{
40
 * Functions to enable the processing and display of HTML forms.
41
 *
42
43
44
45
 * Drupal uses these functions to achieve consistency in its form processing and
 * presentation, while simplifying code and reducing the amount of HTML that
 * must be explicitly generated by modules.
 *
46
47
48
49
 * The primary function used with forms is drupal_get_form(), which is
 * used for forms presented interactively to a user. Forms can also be built and
 * submitted programmatically without any user input using the
 * drupal_form_submit() function.
50
 *
51
52
53
54
55
 * drupal_get_form() handles retrieving, processing, and displaying a rendered
 * HTML form for modules automatically.
 *
 * Here is an example of how to use drupal_get_form() and a form builder
 * function:
56
 * @code
57
58
59
60
61
62
63
 * $form = drupal_get_form('my_module_example_form');
 * ...
 * function my_module_example_form($form, &$form_state) {
 *   $form['submit'] = array(
 *     '#type' => 'submit',
 *     '#value' => t('Submit'),
 *   );
64
 *   return $form;
65
66
67
68
69
70
71
 * }
 * function my_module_example_form_validate($form, &$form_state) {
 *   // Validation logic.
 * }
 * function my_module_example_form_submit($form, &$form_state) {
 *   // Submission logic.
 * }
72
 * @endcode
73
 *
74
75
76
77
78
79
80
81
82
83
 * Or with any number of additional arguments:
 * @code
 * $extra = "extra";
 * $form = drupal_get_form('my_module_example_form', $extra);
 * ...
 * function my_module_example_form($form, &$form_state, $extra) {
 *   $form['submit'] = array(
 *     '#type' => 'submit',
 *     '#value' => $extra,
 *   );
84
 *   return $form;
85
86
 * }
 * @endcode
87
 *
88
89
90
91
 * The $form argument to form-related functions is a structured array containing
 * the elements and properties of the form. For information on the array
 * components and format, and more detailed explanations of the Form API
 * workflow, see the
92
 * @link forms_api_reference.html Form API reference @endlink
93
 * and the
94
 * @link http://drupal.org/node/37775 Form API documentation section. @endlink
95
96
97
98
99
100
101
102
103
 * In addition, there is a set of Form API tutorials in
 * @link form_example_tutorial.inc the Form Example Tutorial @endlink which
 * provide basics all the way up through multistep forms.
 *
 * In the form builder, validation, submission, and other form functions,
 * $form_state is the primary influence on the processing of the form and is
 * passed by reference to most functions, so they use it to communicate with
 * the form system and each other.
 *
104
 * See drupal_build_form() for documentation of $form_state keys.
105
106
107
 */

/**
108
109
 * Returns a renderable form array for a given form ID.
 *
110
111
112
113
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getForm().
114
 */
115
function drupal_get_form($form_arg) {
116
  return call_user_func_array(array(\Drupal::formBuilder(), 'getForm'), func_get_args());
117
118
}

119
/**
120
 * Builds and processes a form for a given form ID.
121
 *
122
123
124
125
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->buildForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::buildForm().
126
127
 */
function drupal_build_form($form_id, &$form_state) {
128
  return \Drupal::formBuilder()->buildForm($form_id, $form_state);
129
}
130

131
/**
132
 * Retrieves default values for the $form_state array.
133
 *
134
135
136
137
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getFormStateDefaults().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getFormStateDefaults().
138
139
 */
function form_state_defaults() {
140
  return \Drupal::formBuilder()->getFormStateDefaults();
141
142
}

143
/**
144
145
 * Constructs a new $form from the information in $form_state.
 *
146
147
148
149
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->rebuildForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::rebuildForm().
150
 */
151
function drupal_rebuild_form($form_id, &$form_state, $old_form = NULL) {
152
  return \Drupal::formBuilder()->rebuildForm($form_id, $form_state, $old_form);
153
154
}

155
/**
156
 * Fetches a form from the cache.
157
 *
158
159
160
161
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getCache().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getCache().
162
163
 */
function form_get_cache($form_build_id, &$form_state) {
164
  return \Drupal::formBuilder()->getCache($form_build_id, $form_state);
165
166
167
}

/**
168
 * Stores a form in the cache.
169
 *
170
171
172
173
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setCache().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::setCache().
174
175
 */
function form_set_cache($form_build_id, $form, $form_state) {
176
  \Drupal::formBuilder()->setCache($form_build_id, $form, $form_state);
177
178
}

179
/**
180
 * Ensures an include file is loaded whenever the form is processed.
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
 *
 * Example:
 * @code
 *   // Load node.admin.inc from Node module.
 *   form_load_include($form_state, 'inc', 'node', 'node.admin');
 * @endcode
 *
 * Use this function instead of module_load_include() from inside a form
 * constructor or any form processing logic as it ensures that the include file
 * is loaded whenever the form is processed. In contrast to using
 * module_load_include() directly, form_load_include() makes sure the include
 * file is correctly loaded also if the form is cached.
 *
 * @param $form_state
 *   The current state of the form.
 * @param $type
 *   The include file's type (file extension).
 * @param $module
 *   The module to which the include file belongs.
 * @param $name
 *   (optional) The base file name (without the $type extension). If omitted,
 *   $module is used; i.e., resulting in "$module.$type" by default.
 *
 * @return
 *   The filepath of the loaded include file, or FALSE if the include file was
 *   not found or has been loaded already.
 *
 * @see module_load_include()
 */
function form_load_include(&$form_state, $type, $module, $name = NULL) {
  if (!isset($name)) {
    $name = $module;
  }
  if (!isset($form_state['build_info']['files']["$module:$name.$type"])) {
    // Only add successfully included files to the form state.
    if ($result = module_load_include($type, $module, $name)) {
      $form_state['build_info']['files']["$module:$name.$type"] = array(
        'type' => $type,
        'module' => $module,
        'name' => $name,
      );
      return $result;
    }
  }
  return FALSE;
}

228
/**
229
230
 * Retrieves, populates, and processes a form.
 *
231
232
233
234
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->submitForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::submitForm().
235
 */
236
function drupal_form_submit($form_arg, &$form_state) {
237
  \Drupal::formBuilder()->submitForm($form_arg, $form_state);
238
239
}

240
241
242
/**
 * Retrieves the structured array that defines a given form.
 *
243
244
245
246
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->retrieveForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::retrieveForm().
247
 */
248
function drupal_retrieve_form($form_id, &$form_state) {
249
  return \Drupal::formBuilder()->retrieveForm($form_id, $form_state);
250

251
252
}
/**
253
254
 * Processes a form submission.
 *
255
256
257
258
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->processForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::processForm().
259
 */
260
function drupal_process_form($form_id, &$form, &$form_state) {
261
  \Drupal::formBuilder()->processForm($form_id, $form, $form_state);
262
263
264
}

/**
265
266
 * Prepares a structured form array.
 *
267
268
269
270
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->prepareForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::prepareForm().
271
 */
272
function drupal_prepare_form($form_id, &$form, &$form_state) {
273
  \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state);
274
275
}

276
/**
277
 * Validates user-submitted form data in the $form_state array.
278
 *
279
280
281
282
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->validateForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::validateForm().
283
 */
284
function drupal_validate_form($form_id, &$form, &$form_state) {
285
  \Drupal::formBuilder()->validateForm($form_id, $form, $form_state);
286
287
}

288
/**
289
290
 * Redirects the user to a URL after a form has been processed.
 *
291
292
293
294
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->redirectForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::redirectForm().
295
 */
296
function drupal_redirect_form($form_state) {
297
  return \Drupal::formBuilder()->redirectForm($form_state);
298
299
}

300
/**
301
302
 * Executes custom validation and submission handlers for a given form.
 *
303
304
305
306
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->executeHandlers().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::executeHandlers().
307
308
 */
function form_execute_handlers($type, &$form, &$form_state) {
309
  \Drupal::formBuilder()->executeHandlers($type, $form, $form_state);
310
311
}

312
/**
313
 * Files an error against a form element.
314
 *
315
316
317
318
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setErrorByName().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::setErrorByName().
319
 */
320
321
function form_set_error($name, array &$form_state, $message = '') {
  \Drupal::formBuilder()->setErrorByName($name, $form_state, $message);
322
323
}

324
/**
325
 * Clears all errors against all form elements made by form_set_error().
326
 *
327
328
329
330
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->clearErrors().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::clearErrors().
331
 */
332
333
function form_clear_error(array &$form_state) {
  \Drupal::formBuilder()->clearErrors($form_state);
334
335
}

336
/**
337
 * Returns an associative array of all errors.
338
 *
339
340
341
342
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getErrors().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getErrors().
343
 */
344
345
function form_get_errors(array &$form_state) {
  return \Drupal::formBuilder()->getErrors($form_state);
346
347
348
}

/**
349
350
 * Returns the error message filed against the given form element.
 *
351
352
353
354
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getError().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getError().
355
 */
356
357
function form_get_error($element, array &$form_state) {
  return \Drupal::formBuilder()->getError($element, $form_state);
358
359
}

360
/**
361
 * Flags an element as having an error.
362
 *
363
364
365
366
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setError().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::setError().
367
 */
368
369
function form_error(&$element, array &$form_state, $message = '') {
  \Drupal::formBuilder()->setError($element, $form_state, $message);
370
371
372
}

/**
373
374
 * Builds and processes all elements in the structured form array.
 *
375
376
377
378
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->doBuildForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::doBuildForm().
379
 */
380
function form_builder($form_id, &$element, &$form_state) {
381
  return \Drupal::formBuilder()->doBuildForm($form_id, $element, $form_state);
382
383
}

384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
 * Removes internal Form API elements and buttons from submitted form values.
 *
 * This function can be used when a module wants to store all submitted form
 * values, for example, by serializing them into a single database column. In
 * such cases, all internal Form API values and all form button elements should
 * not be contained, and this function allows to remove them before the module
 * proceeds to storage. Next to button elements, the following internal values
 * are removed:
 * - form_id
 * - form_token
 * - form_build_id
 * - op
 *
398
 * @param $form_state
399
400
401
402
403
404
405
406
 *   A keyed array containing the current state of the form, including
 *   submitted form values; altered by reference.
 */
function form_state_values_clean(&$form_state) {
  // Remove internal Form API values.
  unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);

  // Remove button values.
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
  // form_builder() collects all button elements in a form. We remove the button
  // value separately for each button element.
  foreach ($form_state['buttons'] as $button) {
    // Remove this button's value from the submitted form values by finding
    // the value corresponding to this button.
    // We iterate over the #parents of this button and move a reference to
    // each parent in $form_state['values']. For example, if #parents is:
    //   array('foo', 'bar', 'baz')
    // then the corresponding $form_state['values'] part will look like this:
    // array(
    //   'foo' => array(
    //     'bar' => array(
    //       'baz' => 'button_value',
    //     ),
    //   ),
    // )
    // We start by (re)moving 'baz' to $last_parent, so we are able unset it
    // at the end of the iteration. Initially, $values will contain a
    // reference to $form_state['values'], but in the iteration we move the
    // reference to $form_state['values']['foo'], and finally to
    // $form_state['values']['foo']['bar'], which is the level where we can
    // unset 'baz' (that is stored in $last_parent).
    $parents = $button['#parents'];
    $last_parent = array_pop($parents);
431
    $key_exists = NULL;
432
    $values = &NestedArray::getValue($form_state['values'], $parents, $key_exists);
433
434
    if ($key_exists && is_array($values)) {
      unset($values[$last_parent]);
435
436
437
438
    }
  }
}

439
/**
440
 * Determines the value for an image button form element.
441
442
443
 *
 * @param $form
 *   The form element whose value is being populated.
444
445
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
446
 *   the element's default value should be returned.
447
 * @param $form_state
448
 *   A keyed array containing the current state of the form.
449
 *
450
451
452
453
 * @return
 *   The data that will appear in the $form_state['values'] collection
 *   for this element. Return nothing to use the default.
 */
454
455
456
function form_type_image_button_value($form, $input, $form_state) {
  if ($input !== FALSE) {
    if (!empty($input)) {
457
458
459
460
461
462
463
464
465
466
      // If we're dealing with Mozilla or Opera, we're lucky. It will
      // return a proper value, and we can get on with things.
      return $form['#return_value'];
    }
    else {
      // Unfortunately, in IE we never get back a proper value for THIS
      // form element. Instead, we get back two split values: one for the
      // X and one for the Y coordinates on which the user clicked the
      // button. We'll find this element in the #post data, and search
      // in the same spot for its name, with '_x'.
467
      $input = $form_state['input'];
468
      foreach (explode('[', $form['#name']) as $element_name) {
469
470
471
472
473
        // chop off the ] that may exist.
        if (substr($element_name, -1) == ']') {
          $element_name = substr($element_name, 0, -1);
        }

474
475
        if (!isset($input[$element_name])) {
          if (isset($input[$element_name . '_x'])) {
476
477
478
479
            return $form['#return_value'];
          }
          return NULL;
        }
480
        $input = $input[$element_name];
481
482
483
484
485
486
      }
      return $form['#return_value'];
    }
  }
}

487
/**
488
 * Determines the value for a checkbox form element.
489
490
 *
 * @param $form
491
 *   The form element whose value is being populated.
492
 * @param $input
493
 *   The incoming input to populate the form element. If this is FALSE,
494
 *   the element's default value should be returned.
495
 *
496
 * @return
497
 *   The data that will appear in the $element_state['values'] collection
498
 *   for this element. Return nothing to use the default.
499
 */
500
function form_type_checkbox_value($element, $input = FALSE) {
501
502
  if ($input === FALSE) {
    // Use #default_value as the default value of a checkbox, except change
503
    // NULL to 0, because FormBuilder::handleInputElement() would otherwise
504
505
506
507
508
509
510
511
512
513
    // replace NULL with empty string, but an empty string is a potentially
    // valid value for a checked checkbox.
    return isset($element['#default_value']) ? $element['#default_value'] : 0;
  }
  else {
    // Checked checkboxes are submitted with a value (possibly '0' or ''):
    // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
    // For checked checkboxes, browsers submit the string version of
    // #return_value, but we return the original #return_value. For unchecked
    // checkboxes, browsers submit nothing at all, but
514
    // FormBuilder::handleInputElement() detects this, and calls this
515
516
517
518
519
520
521
522
523
    // function with $input=NULL. Returning NULL from a value callback means to
    // use the default value, which is not what is wanted when an unchecked
    // checkbox is submitted, so we use integer 0 as the value indicating an
    // unchecked checkbox. Therefore, modules must not use integer 0 as a
    // #return_value, as doing so results in the checkbox always being treated
    // as unchecked. The string '0' is allowed for #return_value. The most
    // common use-case for setting #return_value to either 0 or '0' is for the
    // first option within a 0-indexed array of checkboxes, and for this,
    // form_process_checkboxes() uses the string rather than the integer.
524
    return isset($input) ? $element['#return_value'] : 0;
525
526
527
528
  }
}

/**
529
 * Determines the value for a checkboxes form element.
530
 *
531
 * @param $element
532
 *   The form element whose value is being populated.
533
534
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
535
 *   the element's default value should be returned.
536
 *
537
 * @return
538
 *   The data that will appear in the $element_state['values'] collection
539
 *   for this element. Return nothing to use the default.
540
 */
541
542
function form_type_checkboxes_value($element, $input = FALSE) {
  if ($input === FALSE) {
543
    $value = array();
544
545
    $element += array('#default_value' => array());
    foreach ($element['#default_value'] as $key) {
546
      $value[$key] = $key;
547
548
549
    }
    return $value;
  }
550
551
552
553
554
555
  elseif (is_array($input)) {
    // Programmatic form submissions use NULL to indicate that a checkbox
    // should be unchecked; see drupal_form_submit(). We therefore remove all
    // NULL elements from the array before constructing the return value, to
    // simulate the behavior of web browsers (which do not send unchecked
    // checkboxes to the server at all). This will not affect non-programmatic
556
557
    // form submissions, since all values in \Drupal::request()->request are
    // strings.
558
    foreach ($input as $key => $value) {
559
      if (!isset($value)) {
560
561
562
        unset($input[$key]);
      }
    }
563
    return array_combine($input, $input);
564
  }
565
  else {
566
    return array();
567
  }
568
569
}

570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/**
 * Determines the value of a table form element.
 *
 * @param array $element
 *   The form element whose value is being populated.
 * @param array|false $input
 *   The incoming input to populate the form element. If this is FALSE,
 *   the element's default value should be returned.
 *
 * @return array
 *   The data that will appear in the $form_state['values'] collection
 *   for this element. Return nothing to use the default.
 */
function form_type_table_value(array $element, $input = FALSE) {
  // If #multiple is FALSE, the regular default value of radio buttons is used.
  if (!empty($element['#tableselect']) && !empty($element['#multiple'])) {
    // Contrary to #type 'checkboxes', the default value of checkboxes in a
    // table is built from the array keys (instead of array values) of the
    // #default_value property.
    // @todo D8: Remove this inconsistency.
    if ($input === FALSE) {
      $element += array('#default_value' => array());
592
593
      $value = array_keys(array_filter($element['#default_value']));
      return array_combine($value, $value);
594
595
    }
    else {
596
      return is_array($input) ? array_combine($input, $input) : array();
597
598
599
600
    }
  }
}

601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/**
 * Form value callback: Determines the value for a #type radios form element.
 *
 * @param $element
 *   The form element whose value is being populated.
 * @param $input
 *   (optional) The incoming input to populate the form element. If FALSE, the
 *   element's default value is returned. Defaults to FALSE.
 *
 * @return
 *   The data that will appear in the $element_state['values'] collection for
 *   this element.
 */
function form_type_radios_value(&$element, $input = FALSE) {
  if ($input !== FALSE) {
616
    // When there's user input (including NULL), return it as the value.
617
    // However, if NULL is submitted, FormBuilder::handleInputElement() will
618
619
620
621
    // apply the default value, and we want that validated against #options
    // unless it's empty. (An empty #default_value, such as NULL or FALSE, can
    // be used to indicate that no radio button is selected by default.)
    if (!isset($input) && !empty($element['#default_value'])) {
622
623
624
625
      $element['#needs_validation'] = TRUE;
    }
    return $input;
  }
626
627
628
  else {
    // For default value handling, simply return #default_value. Additionally,
    // for a NULL default value, set #has_garbage_value to prevent
629
    // FormBuilder::handleInputElement() converting the NULL to an empty
630
631
632
633
634
635
636
    // string, so that code can distinguish between nothing selected and the
    // selection of a radio button whose value is an empty string.
    $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
    if (!isset($value)) {
      $element['#has_garbage_value'] = TRUE;
    }
    return $value;
637
638
639
  }
}

640
/**
641
 * Determines the value for a tableselect form element.
642
643
644
645
646
647
 *
 * @param $element
 *   The form element whose value is being populated.
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
 *   the element's default value should be returned.
648
 *
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
 * @return
 *   The data that will appear in the $element_state['values'] collection
 *   for this element. Return nothing to use the default.
 */
function form_type_tableselect_value($element, $input = FALSE) {
  // If $element['#multiple'] == FALSE, then radio buttons are displayed and
  // the default value handling is used.
  if (isset($element['#multiple']) && $element['#multiple']) {
    // Checkboxes are being displayed with the default value coming from the
    // keys of the #default_value property. This differs from the checkboxes
    // element which uses the array values.
    if ($input === FALSE) {
      $value = array();
      $element += array('#default_value' => array());
      foreach ($element['#default_value'] as $key => $flag) {
        if ($flag) {
          $value[$key] = $key;
        }
      }
      return $value;
    }
    else {
671
      return is_array($input) ? array_combine($input, $input) : array();
672
673
674
675
    }
  }
}

676
/**
677
 * Determines the value for a password_confirm form element.
678
 *
679
 * @param $element
680
 *   The form element whose value is being populated.
681
682
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
683
 *   the element's default value should be returned.
684
 *
685
 * @return
686
 *   The data that will appear in the $element_state['values'] collection
687
 *   for this element. Return nothing to use the default.
688
 */
689
690
691
692
function form_type_password_confirm_value($element, $input = FALSE) {
  if ($input === FALSE) {
    $element += array('#default_value' => array());
    return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
693
694
695
696
  }
}

/**
697
 * Determines the value for a select form element.
698
 *
699
 * @param $element
700
 *   The form element whose value is being populated.
701
702
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
703
 *   the element's default value should be returned.
704
 *
705
 * @return
706
 *   The data that will appear in the $element_state['values'] collection
707
 *   for this element. Return nothing to use the default.
708
 */
709
710
711
function form_type_select_value($element, $input = FALSE) {
  if ($input !== FALSE) {
    if (isset($element['#multiple']) && $element['#multiple']) {
712
713
714
715
      // If an enabled multi-select submits NULL, it means all items are
      // unselected. A disabled multi-select always submits NULL, and the
      // default value should be used.
      if (empty($element['#disabled'])) {
716
        return (is_array($input)) ? array_combine($input, $input) : array();
717
718
719
720
      }
      else {
        return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
      }
721
    }
722
723
724
725
726
727
728
729
730
    // Non-multiple select elements may have an empty option preprended to them
    // (see form_process_select()). When this occurs, usually #empty_value is
    // an empty string, but some forms set #empty_value to integer 0 or some
    // other non-string constant. PHP receives all submitted form input as
    // strings, but if the empty option is selected, set the value to match the
    // empty value exactly.
    elseif (isset($element['#empty_value']) && $input === (string) $element['#empty_value']) {
      return $element['#empty_value'];
    }
731
    else {
732
      return $input;
733
734
735
736
737
    }
  }
}

/**
738
 * Determines the value for a textfield form element.
739
 *
740
 * @param $element
741
 *   The form element whose value is being populated.
742
743
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
744
 *   the element's default value should be returned.
745
 *
746
 * @return
747
 *   The data that will appear in the $element_state['values'] collection
748
 *   for this element. Return nothing to use the default.
749
 */
750
function form_type_textfield_value($element, $input = FALSE) {
751
  if ($input !== FALSE && $input !== NULL) {
752
    // Equate $input to the form value to ensure it's marked for
753
    // validation.
754
    return str_replace(array("\r", "\n"), '', $input);
755
756
757
758
  }
}

/**
759
 * Determines the value for form's token value.
760
 *
761
 * @param $element
762
 *   The form element whose value is being populated.
763
764
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
765
 *   the element's default value should be returned.
766
 *
767
 * @return
768
 *   The data that will appear in the $element_state['values'] collection
769
 *   for this element. Return nothing to use the default.
770
 */
771
772
function form_type_token_value($element, $input = FALSE) {
  if ($input !== FALSE) {
773
    return (string) $input;
774
775
776
  }
}

777
/**
778
 * Changes submitted form values during form validation.
779
 *
780
781
782
783
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setValue().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::setValue().
784
 */
785
function form_set_value($element, $value, &$form_state) {
786
  \Drupal::formBuilder()->setValue($element, $value, $form_state);
787
788
}

789
790
791
792
793
794
795
796
797
798
799
800
801
/**
 * Allows PHP array processing of multiple select options with the same value.
 *
 * Used for form select elements which need to validate HTML option groups
 * and multiple options which may return the same value. Associative PHP arrays
 * cannot handle these structures, since they share a common key.
 *
 * @param $array
 *   The form options array to process.
 *
 * @return
 *   An array with all hierarchical elements flattened to a single array.
 *
802
803
804
805
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->flattenOptions().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::flattenOptions().
806
 */
807
808
function form_options_flatten($array) {
  return \Drupal::formBuilder()->flattenOptions($array);
809
810
}

811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
/**
 * Processes a select list form element.
 *
 * This process callback is mandatory for select fields, since all user agents
 * automatically preselect the first available option of single (non-multiple)
 * select lists.
 *
 * @param $element
 *   The form element to process. Properties used:
 *   - #multiple: (optional) Indicates whether one or more options can be
 *     selected. Defaults to FALSE.
 *   - #default_value: Must be NULL or not set in case there is no value for the
 *     element yet, in which case a first default option is inserted by default.
 *     Whether this first option is a valid option depends on whether the field
 *     is #required or not.
 *   - #required: (optional) Whether the user needs to select an option (TRUE)
827
 *     or not (FALSE). Defaults to FALSE.
828
829
830
831
 *   - #empty_option: (optional) The label to show for the first default option.
 *     By default, the label is automatically set to "- Please select -" for a
 *     required field and "- None -" for an optional field.
 *   - #empty_value: (optional) The value for the first default option, which is
832
833
834
835
836
837
838
839
840
841
842
843
 *     used to determine whether the user submitted a value or not.
 *     - If #required is TRUE, this defaults to '' (an empty string).
 *     - If #required is not TRUE and this value isn't set, then no extra option
 *       is added to the select control, leaving the control in a slightly
 *       illogical state, because there's no way for the user to select nothing,
 *       since all user agents automatically preselect the first available
 *       option. But people are used to this being the behavior of select
 *       controls.
 *       @todo Address the above issue in Drupal 8.
 *     - If #required is not TRUE and this value is set (most commonly to an
 *       empty string), then an extra option (see #empty_option above)
 *       representing a "non-selection" is added with this as its value.
844
845
846
847
848
849
850
851
852
853
854
855
856
 *
 * @see _form_validate()
 */
function form_process_select($element) {
  // #multiple select fields need a special #name.
  if ($element['#multiple']) {
    $element['#attributes']['multiple'] = 'multiple';
    $element['#attributes']['name'] = $element['#name'] . '[]';
  }
  // A non-#multiple select needs special handling to prevent user agents from
  // preselecting the first option without intention. #multiple select lists do
  // not get an empty option, as it would not make sense, user interface-wise.
  else {
857
858
859
    // If the element is set to #required through #states, override the
    // element's #required setting.
    $required = isset($element['#states']['required']) ? TRUE : $element['#required'];
860
861
862
863
864
    // If the element is required and there is no #default_value, then add an
    // empty option that will fail validation, so that the user is required to
    // make a choice. Also, if there's a value for #empty_value or
    // #empty_option, then add an option that represents emptiness.
    if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
865
866
      $element += array(
        '#empty_value' => '',
867
        '#empty_option' => $required ? t('- Select -') : t('- None -'),
868
869
870
871
872
873
874
875
876
877
878
      );
      // The empty option is prepended to #options and purposively not merged
      // to prevent another option in #options mistakenly using the same value
      // as #empty_value.
      $empty_option = array($element['#empty_value'] => $element['#empty_option']);
      $element['#options'] = $empty_option + $element['#options'];
    }
  }
  return $element;
}

879
/**
880
881
882
 * Prepares variables for select element templates.
 *
 * Default template: select.html.twig.
883
884
885
886
 *
 * It is possible to group options together; to do this, change the format of
 * $options to an associative array in which the keys are group labels, and the
 * values are associative arrays in the normal $options format.
887
 *
888
889
890
891
892
 * @param $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.
 *     Properties used: #title, #value, #options, #description, #extra,
 *     #multiple, #required, #name, #attributes, #size.
893
 */
894
function template_preprocess_select(&$variables) {
895
  $element = $variables['element'];
896
  element_set_attributes($element, array('id', 'name', 'size'));
897
  _form_set_attributes($element, array('form-select'));
898

899
900
  $variables['attributes'] = $element['#attributes'];
  $variables['options'] = form_select_options($element);
901
902
}

903
/**
904
 * Converts a select form element's options array into HTML.
905
906
907
908
909
910
911
 *
 * @param $element
 *   An associative array containing the properties of the element.
 * @param $choices
 *   Mixed: Either an associative array of items to list as choices, or an
 *   object with an 'option' member that is an associative array. This
 *   parameter is only used internally and should not be passed.
912
 *
913
914
915
 * @return
 *   An HTML string of options for the select form element.
 */
916
917
function form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
918
919
920
    if (empty($element['#options'])) {
      return '';
    }
921
922
    $choices = $element['#options'];
  }
923
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
924
925
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
926
  $value_is_array = $value_valid && is_array($element['#value']);
927
928
  // Check if the element is multiple select and no value has been selected.
  $empty_value = (empty($element['#value']) && !empty($element['#multiple']));
929
930
  $options = '';
  foreach ($choices as $key => $choice) {
931
    if (is_array($choice)) {
932
      $options .= '<optgroup label="' . $key . '">';
933
934
      $options .= form_select_options($element, $choice);
      $options .= '</optgroup>';
935
    }
936
937
938
    elseif (is_object($choice)) {
      $options .= form_select_options($element, $choice->option);
    }
939
    else {
940
      $key = (string) $key;
941
942
      $empty_choice = $empty_value && $key == '_none';
      if ($value_valid && ((!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value']))) || $empty_choice)) {
943
944
945
946
947
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
948
      $options .= '<option value="' . String::checkPlain($key) . '"' . $selected . '>' . String::checkPlain($choice) . '</option>';
949
950
    }
  }
951
  return $options;
952
953
}

954
/**
955
 * Returns the indexes of a select element's options matching a given key.
956
957
 *
 * This function is useful if you need to modify the options that are
958
 * already in a form element; for example, to remove choices which are
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
 * not valid because of additional filters imposed by another module.
 * One example might be altering the choices in a taxonomy selector.
 * To correctly handle the case of a multiple hierarchy taxonomy,
 * #options arrays can now hold an array of objects, instead of a
 * direct mapping of keys to labels, so that multiple choices in the
 * selector can have the same key (and label). This makes it difficult
 * to manipulate directly, which is why this helper function exists.
 *
 * This function does not support optgroups (when the elements of the
 * #options array are themselves arrays), and will return FALSE if
 * arrays are found. The caller must either flatten/restore or
 * manually do their manipulations in this case, since returning the
 * index is not sufficient, and supporting this would make the
 * "helper" too complicated and cumbersome to be of any help.
 *
 * As usual with functions that can return array() or FALSE, do not
 * forget to use === and !== if needed.
976
977
 *
 * @param $element
978
 *   The select element to search.
979
980
 * @param $key
 *   The key to look for.
981
 *
982
 * @return
983
984
 *   An array of indexes that match the given $key. Array will be
 *   empty if no elements were found. FALSE if optgroups were found.
985
 */
986
987
988
989
990
991
function form_get_options($element, $key) {
  $keys = array();
  foreach ($element['#options'] as $index => $choice) {
    if (is_array($choice)) {
      return FALSE;
    }
992
    elseif (is_object($choice)) {
993
994
995
996
      if (isset($choice->option[$key])) {
        $keys[] = $index;
      }
    }
997
    elseif ($index == $key) {
998
      $keys[] = $index;
999
1000
    }
  }
1001
  return $keys;
1002
1003
}

1004
/**
1005
 * Prepares variables for fieldset element templates.
1006
 *
1007
1008
1009
 * Default template: fieldset.html.twig.
 *
 * @param array $variables
1010
1011
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.
1012
1013
 *     Properties used: #attributes, #children, #description, #id, #title,
 *     #value.
1014
 */
1015
function template_preprocess_fieldset(&$variables) {
1016
  $element = $variables['element'];
1017
  element_set_attributes($element, array('id'));
1018
  _form_set_attributes($element, array('form-wrapper'));
1019
1020
  $variables['attributes'] = $element['#attributes'];
  $variables['attributes']['class'][] = 'form-item';
1021

1022
  // If the element is required, a required marker is appended to the label.
1023
  $variables['required'] = '';
1024
  if (!empty($element['#required'])) {
1025
    $variables['required'] = array(
1026
1027
1028
1029
1030
      '#theme' => 'form_required_marker',
      '#element' => $element,
    );
  }

1031
1032
1033
1034
1035
1036
  $variables['prefix'] = isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL;
  $variables['suffix'] = isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL;
  $variables['children'] = $element['#children'];

  // Build legend properties.
  $variables['legend'] = array();
1037
1038
  $legend_attributes = array();
  if (isset($element['#title_display']) && $element['#title_display'] == 'invisible') {
1039
    $legend_attributes['class'][] = 'visually-hidden';
1040
  }
1041
1042
  $variables['legend']['attributes'] = new Attribute($legend_attributes);
  $variables['legend']['title'] = (isset($element['#title']) && $element['#title'] !== '') ? Xss::filterAdmin($element['#title']) : '';
1043

1044
1045
  // Build description properties.
  $variables['description'] = array();
1046
  if (!empty($element['#description'])) {
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
    $description_id = $element['#attributes']['id'] . '--description';
    $description_attributes = array(
      'class' => 'description',
      'id' => $description_id,
    );
    $variables['description']['attributes'] = new Attribute($description_attributes);
    $variables['description']['content'] = $element['#description'];

    // Add the description's id to the fieldset aria attributes.
    $variables['attributes']['aria-describedby'] = $description_id;
1057
  }
1058
1059
}

1060
/**
1061
 * Prepares variables for details element templates.
1062