Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Core / Render / Element / Range.php
1 <?php
2
3 namespace Drupal\Core\Render\Element;
4
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\Core\Render\Element;
7
8 /**
9  * Provides a slider for input of a number within a specific range.
10  *
11  * Provides an HTML5 input element with type of "range".
12  *
13  * Properties:
14  * - #min: Minimum value (defaults to 0).
15  * - #max: Maximum value (defaults to 100).
16  * Refer to \Drupal\Core\Render\Element\Number for additional properties.
17  *
18  * Usage example:
19  * @code
20  * $form['quantity'] = array(
21  *   '#type' => 'range',
22  *   '#title' => $this->t('Quantity'),
23  * );
24  * @endcode
25  *
26  * @see \Drupal\Core\Render\Element\Number
27  *
28  * @FormElement("range")
29  */
30 class Range extends Number {
31
32   /**
33    * {@inheritdoc}
34    */
35   public function getInfo() {
36     $info = parent::getInfo();
37     $class = get_class($this);
38     return [
39       '#min' => 0,
40       '#max' => 100,
41       '#pre_render' => [
42         [$class, 'preRenderRange'],
43       ],
44       '#theme' => 'input__range',
45     ] + $info;
46   }
47
48   /**
49    * Prepares a #type 'range' render element for input.html.twig.
50    *
51    * @param array $element
52    *   An associative array containing the properties of the element.
53    *   Properties used: #title, #value, #description, #min, #max, #attributes,
54    *   #step.
55    *
56    * @return array
57    *   The $element with prepared variables ready for input.html.twig.
58    */
59   public static function preRenderRange($element) {
60     $element['#attributes']['type'] = 'range';
61     Element::setAttributes($element, ['id', 'name', 'value', 'step', 'min', 'max']);
62     static::setAttributes($element, ['form-range']);
63
64     return $element;
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
71     if ($input === '') {
72       $offset = ($element['#max'] - $element['#min']) / 2;
73
74       // Round to the step.
75       if (strtolower($element['#step']) != 'any') {
76         $steps = round($offset / $element['#step']);
77         $offset = $element['#step'] * $steps;
78       }
79
80       return $element['#min'] + $offset;
81     }
82   }
83
84 }