3 namespace Drupal\Core\Render\Element;
5 use Drupal\Core\Render\Element;
8 * Provides a form element for a single radio button.
10 * This is an internal element that is primarily used to render the radios form
11 * element. Refer to \Drupal\Core\Render\Element\Radios for more documentation.
13 * @see \Drupal\Core\Render\Element\Radios
14 * @see \Drupal\Core\Render\Element\Checkbox
16 * @FormElement("radio")
18 class Radio extends FormElement {
23 public function getInfo() {
24 $class = get_class($this);
27 '#default_value' => NULL,
29 [$class, 'processAjaxForm'],
32 [$class, 'preRenderRadio'],
34 '#theme' => 'input__radio',
35 '#theme_wrappers' => ['form_element'],
36 '#title_display' => 'after',
41 * Prepares a #type 'radio' render element for input.html.twig.
43 * @param array $element
44 * An associative array containing the properties of the element.
45 * Properties used: #required, #return_value, #value, #attributes, #title,
46 * #description. The #name property will be sanitized before output. This is
47 * currently done by initializing Drupal\Core\Template\Attribute with all
51 * The $element with prepared variables ready for input.html.twig.
53 public static function preRenderRadio($element) {
54 $element['#attributes']['type'] = 'radio';
55 Element::setAttributes($element, ['id', 'name', '#return_value' => 'value']);
57 // To avoid auto-casting during '==' we convert $element['#value'] and
58 // $element['#return_value'] to strings. It will prevent wrong true-checking
59 // for both cases: 0 == 'string' and 'string' == 0, this will occur because
60 // all numeric array values will be integers and all submitted values will
61 // be strings. Array values are never valid for radios and are skipped. To
62 // account for FALSE and empty string values in the #return_value, we will
63 // consider any #value that evaluates to empty to be the same as any
64 // #return_value that evaluates to empty.
65 if (isset($element['#return_value']) &&
66 $element['#value'] !== FALSE &&
67 !is_array($element['#value']) &&
68 ((empty($element['#value']) && empty($element['#return_value'])) || (string) $element['#value'] === (string) $element['#return_value'])) {
69 $element['#attributes']['checked'] = 'checked';
71 static::setAttributes($element, ['form-radio']);