form.inc 123 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\Form\OptGroup;
15
use Drupal\Core\Render\Element;
16
use Drupal\Core\Template\Attribute;
17
use Drupal\Core\Utility\Color;
18
use Symfony\Component\HttpFoundation\RedirectResponse;
19

20
/**
21
22
23
24
25
26
 * @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
27
 * functions using \@see. Conversely, validate and submit functions should
28
 * reference the form builder function using \@see. For examples, of this see
29
 * system_modules_uninstall() or user_pass(), the latter of which has the
30
 * following in its doxygen documentation:
31
32
33
 * - \@ingroup forms
 * - \@see user_pass_validate()
 * - \@see user_pass_submit()
34
 *
35
 * @}
36
37
38
39
 */

/**
 * @defgroup form_api Form generation
40
 * @{
41
 * Describes how to generate and manipulate forms and process form submissions.
42
 *
43
44
45
 * Drupal provides a Form API in order to achieve consistency in its form
 * processing and presentation, while simplifying code and reducing the amount
 * of HTML that must be explicitly generated by a module.
46
 *
47
48
49
50
51
52
53
54
55
56
 * @section generating_forms Creating forms
 * Forms are defined as classes that implement the
 * \Drupal\Core\Form\FormInterface and are built using the
 * \Drupal\Core\Form\FormBuilder class. Drupal provides a couple of utility
 * classes that can be extended as a starting point for most basic forms, the
 * most commonly used of which is \Drupal\Core\Form\FormBase. FormBuilder
 * handles the low level processing of forms such as rendering the necessary
 * HTML, initial processing of incoming $_POST data, and delegating to your
 * implementation of FormInterface for validation and processing of submitted
 * data.
57
 *
58
 * Here is an example of a Form class:
59
 * @code
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 * namespace Drupal\mymodule\Form;
 *
 * use Drupal\Core\Form\FormBase;
 *
 * class ExampleForm extends FormBase {
 *   public function getFormId() {
 *     // Unique ID of the form.
 *     return 'example_form';
 *   }
 *
 *   public function buildForm(array $form, array &$form_state) {
 *     // Create a $form API array.
 *     $form['phone_number'] = array(
 *       '#type' => 'tel',
 *       '#title' => $this->t('Your phone number')
 *     );
 *     return $form;
 *   }
 *
 *   public function validateForm(array &$form, array &$form_state) {
 *     // Validate submitted form data.
 *   }
 *
 *   public function submitForm(array &$form, array &$form_state) {
 *     // Handle submitted form data.
 *   }
86
 * }
87
 * @endcode
88
 *
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
 * @section retrieving_forms Retrieving and displaying forms
 * \Drupal::formBuilder()->getForm() should be used to handle retrieving,
 * processing, and displaying a rendered HTML form. Given the ExampleForm
 * defined above,
 * \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm') would
 * return the rendered HTML of the form defined by ExampleForm::buildForm(), or
 * call the validateForm() and submitForm(), methods depending on the current
 * processing state.
 *
 * The argument to \Drupal::formBuilder()->getForm() is the name of a class that
 * implements FormBuilderInterface. Any additional arguments passed to the
 * getForm() method will be passed along as additional arguments to the
 * ExampleForm::buildForm() method.
 *
 * For example:
104
 * @code
105
106
 * $extra = '612-123-4567';
 * $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $extra);
107
 * ...
108
109
110
111
 * public function buildForm(array $form, array &$form_state, $extra = NULL)
 *   $form['phone_number'] = array(
 *     '#type' => 'tel',
 *     '#title' => $this->t('Your phone number'),
112
113
 *     '#value' => $extra,
 *   );
114
 *   return $form;
115
116
 * }
 * @endcode
117
 *
118
119
120
121
122
123
124
125
126
127
128
129
130
 * Alternatively, forms can be built directly via the routing system which will
 * take care of calling \Drupal::formBuilder()->getForm(). The following example
 * demonstrates the use of a routing.yml file to display a form at the the
 * given route.
 *
 * @code
 * example.form:
 *   path: '/example-form'
 *   defaults:
 *     _title: 'Example form'
 *     _form: '\Drupal\mymodule\Form\ExampleForm'
 * @endcode
 *
131
132
133
134
 * 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
135
 * @link forms_api_reference.html Form API reference @endlink
136
 * and the
137
 * @link https://drupal.org/node/2117411 Form API documentation section. @endlink
138
139
140
141
 * 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.
 *
142
 * In the form builder, validation, submission, and other form methods,
143
 * $form_state is the primary influence on the processing of the form and is
144
 * passed by reference to most methods, so they can use it to communicate with
145
146
 * the form system and each other.
 *
147
148
 * See \Drupal\Core\Form\FormBuilder::buildForm() for documentation of
 * $form_state keys.
149
150
151
 */

/**
152
153
 * Returns a renderable form array for a given form ID.
 *
154
155
156
157
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getForm().
158
 */
159
function drupal_get_form($form_arg) {
160
  return call_user_func_array(array(\Drupal::formBuilder(), 'getForm'), func_get_args());
161
162
}

163
/**
164
 * Builds and processes a form for a given form ID.
165
 *
166
167
168
169
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->buildForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::buildForm().
170
171
 */
function drupal_build_form($form_id, &$form_state) {
172
  return \Drupal::formBuilder()->buildForm($form_id, $form_state);
173
}
174

175
/**
176
 * Retrieves default values for the $form_state array.
177
 *
178
179
180
181
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getFormStateDefaults().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getFormStateDefaults().
182
183
 */
function form_state_defaults() {
184
  return \Drupal::formBuilder()->getFormStateDefaults();
185
186
}

187
/**
188
189
 * Constructs a new $form from the information in $form_state.
 *
190
191
192
193
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->rebuildForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::rebuildForm().
194
 */
195
function drupal_rebuild_form($form_id, &$form_state, $old_form = NULL) {
196
  return \Drupal::formBuilder()->rebuildForm($form_id, $form_state, $old_form);
197
198
}

199
/**
200
 * Fetches a form from the cache.
201
 *
202
203
204
205
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getCache().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::getCache().
206
207
 */
function form_get_cache($form_build_id, &$form_state) {
208
  return \Drupal::formBuilder()->getCache($form_build_id, $form_state);
209
210
211
}

/**
212
 * Stores a form in the cache.
213
 *
214
215
216
217
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setCache().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::setCache().
218
219
 */
function form_set_cache($form_build_id, $form, $form_state) {
220
  \Drupal::formBuilder()->setCache($form_build_id, $form, $form_state);
221
222
}

223
/**
224
 * Ensures an include file is loaded whenever the form is processed.
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
 *
 * 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;
}

272
/**
273
274
 * Retrieves, populates, and processes a form.
 *
275
276
277
278
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->submitForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::submitForm().
279
 */
280
function drupal_form_submit($form_arg, &$form_state) {
281
  \Drupal::formBuilder()->submitForm($form_arg, $form_state);
282
283
}

284
285
286
/**
 * Retrieves the structured array that defines a given form.
 *
287
288
289
290
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->retrieveForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::retrieveForm().
291
 */
292
function drupal_retrieve_form($form_id, &$form_state) {
293
  return \Drupal::formBuilder()->retrieveForm($form_id, $form_state);
294

295
296
}
/**
297
298
 * Processes a form submission.
 *
299
300
301
302
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->processForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::processForm().
303
 */
304
function drupal_process_form($form_id, &$form, &$form_state) {
305
  \Drupal::formBuilder()->processForm($form_id, $form, $form_state);
306
307
308
}

/**
309
310
 * Prepares a structured form array.
 *
311
312
313
314
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->prepareForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::prepareForm().
315
 */
316
function drupal_prepare_form($form_id, &$form, &$form_state) {
317
  \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state);
318
319
}

320
/**
321
 * Validates user-submitted form data in the $form_state array.
322
 *
323
324
325
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->validateForm().
 *
326
 * @see \Drupal\Core\Form\FormValidatorInterface::validateForm().
327
 */
328
function drupal_validate_form($form_id, &$form, &$form_state) {
329
  \Drupal::formBuilder()->validateForm($form_id, $form, $form_state);
330
331
}

332
/**
333
334
 * Redirects the user to a URL after a form has been processed.
 *
335
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
336
 *   Use \Drupal::service('form_submitter')->redirectForm().
337
 *
338
 * @see \Drupal\Core\Form\FormSubmitterInterface::redirectForm().
339
 */
340
function drupal_redirect_form($form_state) {
341
  return \Drupal::service('form_submitter')->redirectForm($form_state);
342
343
}

344
/**
345
346
 * Executes custom validation and submission handlers for a given form.
 *
347
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
348
 *   Use either \Drupal::service('form_submitter')->executeSubmitHandlers() or
349
 *   \Drupal::service('form_validator')->executeValidateHandlers().
350
 *
351
 * @see \Drupal\Core\Form\FormSubmitterInterface::executeSubmitHandlers()
352
 * @see \Drupal\Core\Form\FormValidatorInterface::executeValidateHandlers()
353
354
 */
function form_execute_handlers($type, &$form, &$form_state) {
355
  if ($type == 'submit') {
356
    \Drupal::service('form_submitter')->executeSubmitHandlers($form, $form_state);
357
358
359
360
  }
  elseif ($type == 'validate') {
    \Drupal::service('form_validator')->executeValidateHandlers($form, $form_state);
  }
361
362
}

363
/**
364
 * Files an error against a form element.
365
 *
366
367
368
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setErrorByName().
 *
369
 * @see \Drupal\Core\Form\FormErrorInterface::setErrorByName().
370
 */
371
372
function form_set_error($name, array &$form_state, $message = '') {
  \Drupal::formBuilder()->setErrorByName($name, $form_state, $message);
373
374
}

375
/**
376
 * Clears all errors against all form elements made by form_set_error().
377
 *
378
379
380
381
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->clearErrors().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::clearErrors().
382
 */
383
384
function form_clear_error(array &$form_state) {
  \Drupal::formBuilder()->clearErrors($form_state);
385
386
}

387
/**
388
 * Returns an associative array of all errors.
389
 *
390
391
392
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getErrors().
 *
393
 * @see \Drupal\Core\Form\FormErrorInterface::getErrors()
394
 */
395
396
function form_get_errors(array &$form_state) {
  return \Drupal::formBuilder()->getErrors($form_state);
397
398
399
}

/**
400
401
 * Returns the error message filed against the given form element.
 *
402
403
404
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->getError().
 *
405
 * @see \Drupal\Core\Form\FormErrorInterface::getError().
406
 */
407
408
function form_get_error($element, array &$form_state) {
  return \Drupal::formBuilder()->getError($element, $form_state);
409
410
}

411
/**
412
 * Flags an element as having an error.
413
 *
414
415
416
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setError().
 *
417
 * @see \Drupal\Core\Form\FormErrorInterface::setError().
418
 */
419
420
function form_error(&$element, array &$form_state, $message = '') {
  \Drupal::formBuilder()->setError($element, $form_state, $message);
421
422
423
}

/**
424
425
 * Builds and processes all elements in the structured form array.
 *
426
427
428
429
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->doBuildForm().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::doBuildForm().
430
 */
431
function form_builder($form_id, &$element, &$form_state) {
432
  return \Drupal::formBuilder()->doBuildForm($form_id, $element, $form_state);
433
434
}

435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
 * 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
 *
449
 * @param $form_state
450
451
452
453
454
455
456
457
 *   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.
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
  // 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);
482
    $key_exists = NULL;
483
    $values = &NestedArray::getValue($form_state['values'], $parents, $key_exists);
484
485
    if ($key_exists && is_array($values)) {
      unset($values[$last_parent]);
486
487
488
489
    }
  }
}

490
/**
491
 * Determines the value for an image button form element.
492
493
494
 *
 * @param $form
 *   The form element whose value is being populated.
495
496
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
497
 *   the element's default value should be returned.
498
 * @param $form_state
499
 *   A keyed array containing the current state of the form.
500
 *
501
502
503
504
 * @return
 *   The data that will appear in the $form_state['values'] collection
 *   for this element. Return nothing to use the default.
 */
505
506
507
function form_type_image_button_value($form, $input, $form_state) {
  if ($input !== FALSE) {
    if (!empty($input)) {
508
509
510
511
512
513
514
515
516
517
      // 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'.
518
      $input = $form_state['input'];
519
      foreach (explode('[', $form['#name']) as $element_name) {
520
521
522
523
524
        // chop off the ] that may exist.
        if (substr($element_name, -1) == ']') {
          $element_name = substr($element_name, 0, -1);
        }

525
526
        if (!isset($input[$element_name])) {
          if (isset($input[$element_name . '_x'])) {
527
528
529
530
            return $form['#return_value'];
          }
          return NULL;
        }
531
        $input = $input[$element_name];
532
533
534
535
536
537
      }
      return $form['#return_value'];
    }
  }
}

538
/**
539
 * Determines the value for a checkbox form element.
540
541
 *
 * @param $form
542
 *   The form element whose value is being populated.
543
 * @param $input
544
 *   The incoming input to populate the form element. If this is FALSE,
545
 *   the element's default value should be returned.
546
 *
547
 * @return
548
 *   The data that will appear in the $element_state['values'] collection
549
 *   for this element. Return nothing to use the default.
550
 */
551
function form_type_checkbox_value($element, $input = FALSE) {
552
553
  if ($input === FALSE) {
    // Use #default_value as the default value of a checkbox, except change
554
    // NULL to 0, because FormBuilder::handleInputElement() would otherwise
555
556
557
558
559
560
561
562
563
564
    // 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
565
    // FormBuilder::handleInputElement() detects this, and calls this
566
567
568
569
570
571
572
573
574
    // 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.
575
    return isset($input) ? $element['#return_value'] : 0;
576
577
578
579
  }
}

/**
580
 * Determines the value for a checkboxes form element.
581
 *
582
 * @param $element
583
 *   The form element whose value is being populated.
584
585
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
586
 *   the element's default value should be returned.
587
 *
588
 * @return
589
 *   The data that will appear in the $element_state['values'] collection
590
 *   for this element. Return nothing to use the default.
591
 */
592
593
function form_type_checkboxes_value($element, $input = FALSE) {
  if ($input === FALSE) {
594
    $value = array();
595
596
    $element += array('#default_value' => array());
    foreach ($element['#default_value'] as $key) {
597
      $value[$key] = $key;
598
599
600
    }
    return $value;
  }
601
602
603
604
605
606
  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
607
608
    // form submissions, since all values in \Drupal::request()->request are
    // strings.
609
    foreach ($input as $key => $value) {
610
      if (!isset($value)) {
611
612
613
        unset($input[$key]);
      }
    }
614
    return array_combine($input, $input);
615
  }
616
  else {
617
    return array();
618
  }
619
620
}

621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/**
 * 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());
643
644
      $value = array_keys(array_filter($element['#default_value']));
      return array_combine($value, $value);
645
646
    }
    else {
647
      return is_array($input) ? array_combine($input, $input) : array();
648
649
650
651
    }
  }
}

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/**
 * 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) {
667
    // When there's user input (including NULL), return it as the value.
668
    // However, if NULL is submitted, FormBuilder::handleInputElement() will
669
670
671
672
    // 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'])) {
673
674
675
676
      $element['#needs_validation'] = TRUE;
    }
    return $input;
  }
677
678
679
  else {
    // For default value handling, simply return #default_value. Additionally,
    // for a NULL default value, set #has_garbage_value to prevent
680
    // FormBuilder::handleInputElement() converting the NULL to an empty
681
682
683
684
685
686
687
    // 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;
688
689
690
  }
}

691
/**
692
 * Determines the value for a tableselect form element.
693
694
695
696
697
698
 *
 * @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.
699
 *
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
 * @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 {
722
      return is_array($input) ? array_combine($input, $input) : array();
723
724
725
726
    }
  }
}

727
/**
728
 * Determines the value for a password_confirm form element.
729
 *
730
 * @param $element
731
 *   The form element whose value is being populated.
732
733
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
734
 *   the element's default value should be returned.
735
 *
736
 * @return
737
 *   The data that will appear in the $element_state['values'] collection
738
 *   for this element. Return nothing to use the default.
739
 */
740
741
742
743
function form_type_password_confirm_value($element, $input = FALSE) {
  if ($input === FALSE) {
    $element += array('#default_value' => array());
    return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
744
745
746
747
  }
}

/**
748
 * Determines the value for a select form element.
749
 *
750
 * @param $element
751
 *   The form element whose value is being populated.
752
753
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
754
 *   the element's default value should be returned.
755
 *
756
 * @return
757
 *   The data that will appear in the $element_state['values'] collection
758
 *   for this element. Return nothing to use the default.
759
 */
760
761
762
function form_type_select_value($element, $input = FALSE) {
  if ($input !== FALSE) {
    if (isset($element['#multiple']) && $element['#multiple']) {
763
764
765
766
      // 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'])) {
767
        return (is_array($input)) ? array_combine($input, $input) : array();
768
769
770
771
      }
      else {
        return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
      }
772
    }
773
774
775
776
777
778
779
780
781
    // 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'];
    }
782
    else {
783
      return $input;
784
785
786
787
788
    }
  }
}

/**
789
 * Determines the value for a textfield form element.
790
 *
791
 * @param $element
792
 *   The form element whose value is being populated.
793
794
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
795
 *   the element's default value should be returned.
796
 *
797
 * @return
798
 *   The data that will appear in the $element_state['values'] collection
799
 *   for this element. Return nothing to use the default.
800
 */
801
function form_type_textfield_value($element, $input = FALSE) {
802
  if ($input !== FALSE && $input !== NULL) {
803
    // Equate $input to the form value to ensure it's marked for
804
    // validation.
805
    return str_replace(array("\r", "\n"), '', $input);
806
807
808
809
  }
}

/**
810
 * Determines the value for form's token value.
811
 *
812
 * @param $element
813
 *   The form element whose value is being populated.
814
815
 * @param $input
 *   The incoming input to populate the form element. If this is FALSE,
816
 *   the element's default value should be returned.
817
 *
818
 * @return
819
 *   The data that will appear in the $element_state['values'] collection
820
 *   for this element. Return nothing to use the default.
821
 */
822
823
function form_type_token_value($element, $input = FALSE) {
  if ($input !== FALSE) {
824
    return (string) $input;
825
826
827
  }
}

828
/**
829
 * Changes submitted form values during form validation.
830
 *
831
832
833
834
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
 *   Use \Drupal::formBuilder()->setValue().
 *
 * @see \Drupal\Core\Form\FormBuilderInterface::setValue().
835
 */
836
function form_set_value($element, $value, &$form_state) {
837
  \Drupal::formBuilder()->setValue($element, $value, $form_state);
838
839
}

840
841
842
843
844
845
846
847
848
849
850
851
852
/**
 * 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.
 *
853
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
854
 *   Use \Drupal\Core\Form\OptGroup::flattenOptions().
855
 */
856
function form_options_flatten($array) {
857
  return OptGroup::flattenOptions($array);
858
859
}

860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
/**
 * 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)
876
 *     or not (FALSE). Defaults to FALSE.
877
878
879
880
 *   - #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
881
882
883
884
885
886
887
888
889
890
891
892
 *     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.
893
894
895
896
897
898
899
900
901
902
903
904
905
 *
 * @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 {
906
907
908
    // If the element is set to #required through #states, override the
    // element's #required setting.
    $required = isset($element['#states']['required']) ? TRUE : $element['#required'];
909
910
911
912
913
    // 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'])) {
914
915
      $element += array(
        '#empty_value' => '',
916
        '#empty_option' => $required ? t('- Select -') : t('- None -'),
917
918
919
920
921
922
923
924
925
926
927
      );
      // 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;
}

928
/**
929
930
931
 * Prepares variables for select element templates.
 *
 * Default template: select.html.twig.
932
933
934
935
 *
 * 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.
936
 *
937
938
939
940
941
 * @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.
942
 */
943
function template_preprocess_select(&$variables) {
944
  $element = $variables['element'];
945
  Element::setAttributes($element, array('id', 'name', 'size'));
946
  _form_set_attributes($element, array('form-select'));
947

948
949
  $variables['attributes'] = $element['#attributes'];
  $variables['options'] = form_select_options($element);
950
951
}

952
/**
953
 * Converts a select form element's options array into HTML.
954
955
956
957
958
959
960
 *
 * @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.
961
 *
962
963
964
 * @return
 *   An HTML string of options for the select form element.
 */
965
966
function form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
967
968
969
    if (empty($element['#options'])) {
      return '';
    }
970
971
    $choices = $element['#options'];
  }
972
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
973
974
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
975
  $value_is_array = $value_valid && is_array($element['#value']);
976
977
  // Check if the element is multiple select and no value has been selected.
  $empty_value = (empty($element['#value']) && !empty($element['#multiple']));
978
979
  $options = '';
  foreach ($choices as $key => $choice) {
980
    if (is_array($choice)) {
981
      $options .= '<optgroup label="' . $key . '">';
982
983
      $options .= form_select_options($element, $choice);
      $options .= '</optgroup>';
984
    }
985
    elseif (is_object($choice) && isset($choice->option)) {
986
987
      $options .= form_select_options($element, $choice->option);
    }
988
    else {
989
      $key = (string) $key;
990
991
      $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)) {
992
993
994
995
996
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
997
      $options .= '<option value="' . String::checkPlain($key) . '"' . $selected . '>' . String::checkPlain($choice) . '</option>';
998
999
    }
  }
1000
  return $options;
1001
1002
}

1003
/**
1004
 * Returns the indexes of a select element's options matching a given key.
1005
1006
 *
 * This function is useful if you need to modify the options that are
1007
 * already in a form element; for example, to remove choices which are
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
 * 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.
1025
1026
 *
 * @param $element
1027
 *   The select element to search.
1028
1029
 * @param $key
 *   The key to look for.
1030
 *
1031
 * @return
1032
1033
 *   An array of indexes that match the given $key. Array will be
 *   empty if no elements were found. FALSE if optgroups were found.
1034
 */
1035
1036
1037
1038
1039
1040
function form_get_options($element, $key) {
  $keys = array();
  foreach ($element['#options'] as $index => $choice) {
    if (is_array($choice)) {
      return FALSE;
    }
1041
    elseif (is_object($choice)) {
1042
1043
1044
1045
      if (isset($choice->option[$key])) {
        $keys[] = $index;
      }
    }
1046
    elseif ($index == $key) {
1047
      $keys[] = $index;
1048
1049
    }
  }
1050
  return $keys;
1051
1052
}

1053
/**
1054
 * Prepares variables for fieldset element templates.
1055
 *
1056
1057
1058
 * Default template: fieldset.html.twig.
 *
 * @param array $variables
1059
1060
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.