function Checkboxes::valueCallback

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

Overrides FormElement::valueCallback

File

core/lib/Drupal/Core/Render/Element/Checkboxes.php, line 109

Class

Checkboxes
Provides a form element for a set of checkboxes.

Namespace

Drupal\Core\Render\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {
        $value = [];
        $element += [
            '#default_value' => [],
        ];
        foreach ($element['#default_value'] as $key) {
            $value[$key] = $key;
        }
        return $value;
    }
    elseif (is_array($input)) {
        // Programmatic form submissions use NULL to indicate that a checkbox
        // should be unchecked. We therefore remove all NULL elements from the
        // array before constructing the return value, to simulate the behavior
        // of web browsers (which do not send unchecked checkboxes to the server
        // at all). This will not affect non-programmatic form submissions, since
        // all values in \Drupal::request()->request are strings.
        // @see \Drupal\Core\Form\FormBuilderInterface::submitForm()
        foreach ($input as $key => $value) {
            if (!isset($value)) {
                unset($input[$key]);
            }
        }
        // Because the disabled checkboxes don't receive their input from the
        // form submission, we use their default value.
        if (!empty($element['#default_value'])) {
            foreach ($element['#default_value'] as $key) {
                if (!empty($element[$key]['#disabled'])) {
                    $input[$key] = $key;
                }
            }
        }
        return array_combine($input, $input);
    }
    else {
        return [];
    }
}

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