function Checkbox::valueCallback

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Render/Element/Checkbox.php \Drupal\Core\Render\Element\Checkbox::valueCallback()
  2. 8.9.x core/lib/Drupal/Core/Render/Element/Checkbox.php \Drupal\Core\Render\Element\Checkbox::valueCallback()
  3. 10 core/lib/Drupal/Core/Render/Element/Checkbox.php \Drupal\Core\Render\Element\Checkbox::valueCallback()

Overrides FormElementBase::valueCallback

File

core/lib/Drupal/Core/Render/Element/Checkbox.php, line 54

Class

Checkbox
Provides a form element for a single checkbox.

Namespace

Drupal\Core\Render\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {
        // Use #default_value as the default value of a checkbox, except change
        // NULL to 0, because FormBuilder::handleInputElement() would otherwise
        // replace NULL with empty string, but an empty string is a potentially
        // valid value for a checked checkbox.
        return $element['#default_value'] ?? 0;
    }
    else {
        // Checked checkboxes are submitted with a value (possibly '0' or ''):
        // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
        // For checked checkboxes, browsers submit the string version of
        // #return_value, but we return the original #return_value. For unchecked
        // checkboxes, browsers submit nothing at all, but
        // FormBuilder::handleInputElement() detects this, and calls this
        // function with $input=NULL. Returning NULL from a value callback means
        // to use the default value, which is not what is wanted when an unchecked
        // checkbox is submitted, so we use integer 0 as the value indicating an
        // unchecked checkbox. Therefore, modules must not use integer 0 as a
        // #return_value, as doing so results in the checkbox always being treated
        // as unchecked. The string '0' is allowed for #return_value. The most
        // common use-case for setting #return_value to either 0 or '0' is for the
        // first option within a 0-indexed array of checkboxes, and for this,
        // \Drupal\Core\Render\Element\Checkboxes::processCheckboxes() uses the
        // string rather than the integer.
        return isset($input) ? $element['#return_value'] : 0;
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.