Same name and namespace in other branches
  1. 8.x-2.x src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php \Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetSpectrum::formElement() 1 comment

Overrides ColorFieldWidgetBase::formElement

File

src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php, line 112

Class

ColorFieldWidgetSpectrum
Plugin implementation of the color_field spectrum widget.

Namespace

Drupal\color_field\Plugin\Field\FieldWidget

Code

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) : array {
    $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])) {
            continue;
        }
        $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;
}