ColorFieldFormatterSwatchOptions.php in Color Field 8.2
File
src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatchOptions.php
View source
<?php
namespace Drupal\color_field\Plugin\Field\FieldFormatter;
use Drupal\color_field\Plugin\Field\FieldType\ColorFieldType;
use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\color_field\ColorHex;
use Drupal\Core\Template\Attribute;
class ColorFieldFormatterSwatchOptions extends ColorFieldFormatterSwatch {
public function viewElements(FieldItemListInterface $items, $langcode) {
$settings = $this
->getSettings();
$elements = [];
$name = Html::getUniqueId("color-field");
foreach ($items as $delta => $item) {
$hex = $this
->viewRawValue($item);
$id = Html::getUniqueId("color-field-{$hex}");
$elements[$delta] = [
'#theme' => 'color_field_formatter_swatch_option',
'#id' => $id,
'#name' => $name,
'#input_type' => $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple() ? 'checkbox' : 'radio',
'#value' => $hex,
'#shape' => $settings['shape'],
'#height' => is_numeric($settings['height']) ? "{$settings['height']}px" : $settings['height'],
'#width' => is_numeric($settings['width']) ? "{$settings['width']}px" : $settings['width'],
'#color' => $this
->viewValue($item),
'#attributes' => new Attribute([
'class' => [
"color_field__swatch--{$settings['shape']}",
],
]),
];
if ($settings['data_attribute']) {
$elements[$delta]['#attributes']['data-color'] = $hex;
}
}
return $elements;
}
protected function viewRawValue(ColorFieldType $item) {
return (new ColorHex($item->color, $item->opacity))
->toString(FALSE);
}
}