View source
<?php
namespace Drupal\jquery_colorpicker\Element;
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
class JQueryColorpickerElement extends FormElement {
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#maxlength' => 7,
'#size' => 7,
'#element_validate' => [
[
$class,
'validateElement',
],
],
'#jquery_colorpicker_background' => 'select.png',
'#pre_render' => [
[
$class,
'preRenderjQueryColorpicker',
],
],
'#process' => [
'Drupal\\Core\\Render\\Element\\RenderElement::processAjaxForm',
[
$class,
'processElement',
],
],
'#theme' => 'jquery_colorpicker',
'#theme_wrappers' => [
'form_element',
],
'#attached' => [
'library' => [
'jquery_colorpicker/element',
],
],
];
}
public static function validateElement(&$element, FormStateInterface $form_state) {
if (strlen($element['#value'])) {
$valid_color = \Drupal::service('colorapi.service')
->isValidHexadecimalColorString($element['#value']);
if (!$valid_color) {
$form_state
->setError($element, t('@value is not a valid hexidecimal color.', [
'@value' => $element['#value'],
]));
}
}
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if ($input !== FALSE && $input !== NULL && is_scalar($input)) {
if (\Drupal::service('colorapi.service')
->isValidHexadecimalColorString($input)) {
return strtoupper($input);
}
}
return NULL;
}
public static function preRenderjQueryColorpicker(array $element) {
$element['#attributes']['type'] = 'text';
Element::setAttributes($element, [
'id',
'name',
'value',
'size',
'maxlength',
]);
static::setAttributes($element, [
'form-jquery_colorpicker',
]);
return $element;
}
public static function processElement(&$element, FormStateInterface $form_state, &$complete_form) {
$element['#id'] = Html::getUniqueID('edit-' . implode('-', $element['#parents']));
$backgrounds = [
'select.png',
'select2.png',
];
$background = isset($element['#jquery_colorpicker_background']) && in_array($element['#jquery_colorpicker_background'], $backgrounds) ? $element['#jquery_colorpicker_background'] : 'select.png';
$background_url = file_create_url('vendor://jaypan/jquery-colorpicker/images/' . $background);
$element['#attached']['drupalSettings']['jqueryColorpicker']['elements'][$element['#id']]['background'] = $background_url;
return $element;
}
}