Same name and namespace in other branches
- 3.0.x src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php \Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetSpectrum::formElement()
Overrides ColorFieldWidgetBase::formElement
Fichier
-
src/
Plugin/ Field/ FieldWidget/ ColorFieldWidgetSpectrum.php, line 127
Classe
- ColorFieldWidgetSpectrum
- Plugin implementation of the color_field spectrum widget.
Namespace
Drupal\color_field\Plugin\Field\FieldWidgetCode
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element['#attached']['library'][] = 'color_field/color-field-widget-spectrum';
// Set Drupal settings.
$settings = $this->getSettings();
// Compare with default settings make sure they are the same datatype.
$defaults = self::defaultSettings();
foreach ($settings as $key => $value) {
if (is_bool($defaults[$key])) {
$settings[$key] = boolval($value);
}
}
// Parsing Palette data so that it works with spectrum color picker.
// This will create a multidimensional array of hex values.
// Do some cleanup to reduce risk of malformed data.
if (!empty($settings['palette'])) {
// Remove any whitespace.
$settings['palette'] = str_replace([
' ',
"\n",
'"',
"'",
], '', $settings['palette']);
// Parse each row first and reset the palette.
$rows = explode("\r", $settings['palette']);
$settings['palette'] = [];
// Support all kinds of color modes.
$re = '/(rgba|hsva|hsla)[\\(\\s][0-9]*[%\\,\\s]+[0-9]*[%\\,\\s]+[0-9]*[%\\,\\s]+[0-9\\.]+[\\)\\s]*|(rgb|hsv|hsl)[\\(\\s][0-9]+[%\\,\\s]+[0-9]+[%\\,\\s]+[0-9]+[\\)\\s]*|[\\#]?[0-9a-f]+|[a-z]+/mi';
foreach ($rows as $row) {
// Next explode each row into an array of values.
preg_match_all($re, $row, $matches);
$settings['palette'][] = $matches[0];
}
}
$settings['show_alpha'] = (bool) $this->getFieldSetting('opacity');
$element['#attributes']['id'] = $element['#uid'];
$element['#attributes']['class'][] = 'js-color-field-widget-spectrum';
$element['#attached']['drupalSettings']['color_field']['color_field_widget_spectrum'][$element['#uid']] = $settings;
$element['color']['#attributes']['class'][] = 'js-color-field-widget-spectrum__color';
$element['opacity']['#attributes']['class'][] = 'js-color-field-widget-spectrum__opacity';
return $element;
}