You are here

public static function Radios::valueCallback in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Render/Element/Radios.php \Drupal\Core\Render\Element\Radios::valueCallback()
  2. 9 core/lib/Drupal/Core/Render/Element/Radios.php \Drupal\Core\Render\Element\Radios::valueCallback()

Determines how user input is mapped to an element's #value property.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

mixed The value to assign to the element.

Overrides FormElement::valueCallback

File

core/lib/Drupal/Core/Render/Element/Radios.php, line 99

Class

Radios
Provides a form element for a set of radio buttons.

Namespace

Drupal\Core\Render\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  if ($input !== FALSE) {

    // When there's user input (including NULL), return it as the value.
    // However, if NULL is submitted, FormBuilder::handleInputElement() will
    // 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'])) {
      $element['#needs_validation'] = TRUE;
    }
    return $input;
  }
  else {

    // For default value handling, simply return #default_value. Additionally,
    // for a NULL default value, set #has_garbage_value to prevent
    // FormBuilder::handleInputElement() converting the NULL to an empty
    // string, so that code can distinguish between nothing selected and the
    // selection of a radio button whose value is an empty string.
    $value = $element['#default_value'] ?? NULL;
    if (!isset($value)) {
      $element['#has_garbage_value'] = TRUE;
    }
    return $value;
  }
}