Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Core / Render / Element / Weight.php
1 <?php
2
3 namespace Drupal\Core\Render\Element;
4
5 use Drupal\Core\Form\FormStateInterface;
6
7 /**
8  * Provides a form element for input of a weight.
9  *
10  * Weights are integers used to indicate ordering, with larger numbers later in
11  * the order.
12  *
13  * Properties:
14  * - #delta: The range of possible weight values used. A delta of 10 would
15  *   indicate possible weight values between -10 and 10.
16  *
17  * Usage example:
18  * @code
19  * $form['weight'] = array(
20  *   '#type' => 'weight',
21  *   '#title' => $this->t('Weight'),
22  *   '#default_value' => $edit['weight'],
23  *   '#delta' => 10,
24  * );
25  * @endcode
26  *
27  * @FormElement("weight")
28  */
29 class Weight extends FormElement {
30
31   /**
32    * {@inheritdoc}
33    */
34   public function getInfo() {
35     $class = get_class($this);
36     return [
37       '#input' => TRUE,
38       '#delta' => 10,
39       '#default_value' => 0,
40       '#process' => [
41         [$class, 'processWeight'],
42         [$class, 'processAjaxForm'],
43       ],
44     ];
45   }
46
47   /**
48    * Expands a weight element into a select element.
49    */
50   public static function processWeight(&$element, FormStateInterface $form_state, &$complete_form) {
51     $element['#is_weight'] = TRUE;
52
53     $element_info_manager = \Drupal::service('element_info');
54     // If the number of options is small enough, use a select field.
55     $max_elements = \Drupal::config('system.site')->get('weight_select_max');
56     if ($element['#delta'] <= $max_elements) {
57       $element['#type'] = 'select';
58       $weights = [];
59       for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
60         $weights[$n] = $n;
61       }
62       $default_value = (int) $element['#default_value'];
63       if (!isset($weights[$default_value])) {
64         $weights[$default_value] = $default_value;
65         ksort($weights);
66       }
67       $element['#options'] = $weights;
68       $element += $element_info_manager->getInfo('select');
69     }
70     // Otherwise, use a text field.
71     else {
72       $element['#type'] = 'number';
73       // Use a field big enough to fit most weights.
74       $element['#size'] = 10;
75       $element += $element_info_manager->getInfo('number');
76     }
77
78     return $element;
79   }
80
81 }