1<?php
2
3namespace Drupal\Core\Render\Element;
4
5use Drupal\Core\Form\FormStateInterface;
6use Drupal\Component\Utility\Html as HtmlUtility;
7
8/**
9 * Provides a form element for a set of radio buttons.
10 *
11 * Properties:
12 * - #options: An associative array, where the keys are the returned values for
13 *   each radio button, and the values are the labels next to each radio button.
14 *
15 * Usage example:
16 * @code
17 * $form['settings']['active'] = array(
18 *   '#type' => 'radios',
19 *   '#title' => $this->t('Poll status'),
20 *   '#default_value' => 1,
21 *   '#options' => array(0 => $this->t('Closed'), 1 => $this->t('Active')),
22 * );
23 * @endcode
24 *
25 * @see \Drupal\Core\Render\Element\Checkboxes
26 * @see \Drupal\Core\Render\Element\Radio
27 * @see \Drupal\Core\Render\Element\Select
28 *
29 * @FormElement("radios")
30 */
31class Radios extends FormElement {
32
33  use CompositeFormElementTrait;
34
35  /**
36   * {@inheritdoc}
37   */
38  public function getInfo() {
39    $class = get_class($this);
40    return [
41      '#input' => TRUE,
42      '#process' => [
43        [$class, 'processRadios'],
44      ],
45      '#theme_wrappers' => ['radios'],
46      '#pre_render' => [
47        [$class, 'preRenderCompositeFormElement'],
48      ],
49    ];
50  }
51
52  /**
53   * Expands a radios element into individual radio elements.
54   */
55  public static function processRadios(&$element, FormStateInterface $form_state, &$complete_form) {
56    if (count($element['#options']) > 0) {
57      $weight = 0;
58      foreach ($element['#options'] as $key => $choice) {
59        // Maintain order of options as defined in #options, in case the element
60        // defines custom option sub-elements, but does not define all option
61        // sub-elements.
62        $weight += 0.001;
63
64        $element += [$key => []];
65        // Generate the parents as the autogenerator does, so we will have a
66        // unique id for each radio button.
67        $parents_for_id = array_merge($element['#parents'], [$key]);
68        $element[$key] += [
69          '#type' => 'radio',
70          '#title' => $choice,
71          // The key is sanitized in Drupal\Core\Template\Attribute during output
72          // from the theme function.
73          '#return_value' => $key,
74          // Use default or FALSE. A value of FALSE means that the radio button is
75          // not 'checked'.
76          '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : FALSE,
77          '#attributes' => $element['#attributes'],
78          '#parents' => $element['#parents'],
79          '#id' => HtmlUtility::getUniqueId('edit-' . implode('-', $parents_for_id)),
80          '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
81          // Errors should only be shown on the parent radios element.
82          '#error_no_message' => TRUE,
83          '#weight' => $weight,
84        ];
85      }
86    }
87    return $element;
88  }
89
90  /**
91   * {@inheritdoc}
92   */
93  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
94    if ($input !== FALSE) {
95      // When there's user input (including NULL), return it as the value.
96      // However, if NULL is submitted, FormBuilder::handleInputElement() will
97      // apply the default value, and we want that validated against #options
98      // unless it's empty. (An empty #default_value, such as NULL or FALSE, can
99      // be used to indicate that no radio button is selected by default.)
100      if (!isset($input) && !empty($element['#default_value'])) {
101        $element['#needs_validation'] = TRUE;
102      }
103      return $input;
104    }
105    else {
106      // For default value handling, simply return #default_value. Additionally,
107      // for a NULL default value, set #has_garbage_value to prevent
108      // FormBuilder::handleInputElement() converting the NULL to an empty
109      // string, so that code can distinguish between nothing selected and the
110      // selection of a radio button whose value is an empty string.
111      $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
112      if (!isset($value)) {
113        $element['#has_garbage_value'] = TRUE;
114      }
115      return $value;
116    }
117  }
118
119}
120