Same filename in this branch
- 10 core/lib/Drupal/Component/Utility/Color.php
- 10 core/lib/Drupal/Core/Render/Element/Color.php
Same filename and directory in other branches
- 8.9.x core/lib/Drupal/Core/Render/Element/Color.php
- 9 core/lib/Drupal/Core/Render/Element/Color.php
Namespace
Drupal\Core\Render\Element
File
core/lib/Drupal/Core/Render/Element/Color.php
View source
<?php
namespace Drupal\Core\Render\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Attribute\FormElement;
use Drupal\Core\Render\Element;
use Drupal\Component\Utility\Color as ColorUtility;
class Color extends FormElementBase {
public function getInfo() {
$class = static::class;
return [
'#input' => TRUE,
'#process' => [
[
$class,
'processAjaxForm',
],
],
'#element_validate' => [
[
$class,
'validateColor',
],
],
'#pre_render' => [
[
$class,
'preRenderColor',
],
],
'#theme' => 'input__color',
'#theme_wrappers' => [
'form_element',
],
];
}
public static function validateColor(&$element, FormStateInterface $form_state, &$complete_form) {
$value = trim($element['#value']);
if ($value === '') {
$form_state
->setValueForElement($element, '#000000');
}
else {
try {
$form_state
->setValueForElement($element, ColorUtility::rgbToHex(ColorUtility::hexToRgb($value)));
} catch (\InvalidArgumentException $e) {
$form_state
->setError($element, t('%name must be a valid color.', [
'%name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title'],
]));
}
}
}
public static function preRenderColor($element) {
$element['#attributes']['type'] = 'color';
Element::setAttributes($element, [
'id',
'name',
'value',
]);
static::setAttributes($element, [
'form-color',
]);
return $element;
}
}
Classes