function Color::validateColor

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

Form element validation handler for #type 'color'.

File

core/lib/Drupal/Core/Render/Element/Color.php, line 52

Class

Color
Provides a form element for choosing a color.

Namespace

Drupal\Core\Render\Element

Code

public static function validateColor(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = trim($element['#value']);
    // Default to black if no value is given.
    // @see https://www.w3.org/TR/html5/number-state.html#color-state
    if ($value === '') {
        $form_state->setValueForElement($element, '#000000');
    }
    else {
        // Try to parse the value and normalize it.
        try {
            $form_state->setValueForElement($element, ColorUtility::rgbToHex(ColorUtility::hexToRgb($value)));
        } catch (\InvalidArgumentException) {
            $form_state->setError($element, t('%name must be a valid color.', [
                '%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title'],
            ]));
        }
    }
}

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