3 namespace Drupal\Core\Render\Element;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\Core\Render\Element;
7 use Drupal\Component\Utility\Color as ColorUtility;
10 * Provides a form element for choosing a color.
13 * - #default_value: Default value, in a format like #ffffff.
17 * $form['color'] = array(
19 * '#title' => $this->t('Color'),
20 * '#default_value' => '#ffffff',
24 * @FormElement("color")
26 class Color extends FormElement {
31 public function getInfo() {
32 $class = get_class($this);
36 [$class, 'processAjaxForm'],
38 '#element_validate' => [
39 [$class, 'validateColor'],
42 [$class, 'preRenderColor'],
44 '#theme' => 'input__color',
45 '#theme_wrappers' => ['form_element'],
50 * Form element validation handler for #type 'color'.
52 public static function validateColor(&$element, FormStateInterface $form_state, &$complete_form) {
53 $value = trim($element['#value']);
55 // Default to black if no value is given.
56 // @see http://www.w3.org/TR/html5/number-state.html#color-state
58 $form_state->setValueForElement($element, '#000000');
61 // Try to parse the value and normalize it.
63 $form_state->setValueForElement($element, ColorUtility::rgbToHex(ColorUtility::hexToRgb($value)));
65 catch (\InvalidArgumentException $e) {
66 $form_state->setError($element, t('%name must be a valid color.', ['%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title']]));
72 * Prepares a #type 'color' render element for input.html.twig.
74 * @param array $element
75 * An associative array containing the properties of the element.
76 * Properties used: #title, #value, #description, #attributes.
79 * The $element with prepared variables ready for input.html.twig.
81 public static function preRenderColor($element) {
82 $element['#attributes']['type'] = 'color';
83 Element::setAttributes($element, ['id', 'name', 'value']);
84 static::setAttributes($element, ['form-color']);