ColorFieldSwatchFormatter.php in Color Field 8
File
src/Plugin/Field/FieldFormatter/ColorFieldSwatchFormatter.php
View source
<?php
namespace Drupal\color_field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
class ColorFieldSwatchFormatter extends FormatterBase {
public static function defaultSettings() {
return array(
'width' => 50,
'height' => 50,
) + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['width'] = array(
'#type' => 'number',
'#title' => t('Width'),
'#default_value' => $this
->getSetting('width'),
'#min' => 1,
'#description' => t(''),
);
$elements['height'] = array(
'#type' => 'number',
'#title' => t('Height'),
'#default_value' => $this
->getSetting('height'),
'#min' => 1,
'#description' => t(''),
);
return $elements;
}
public function settingsSummary() {
$summary = array();
$settings = $this
->getSettings();
$summary[] = t('Width: @width Height: @height', array(
'@width' => $settings['width'],
'@height' => $settings['height'],
));
return $summary;
}
public function viewElements(FieldItemListInterface $items) {
$elements = array();
$settings = $this
->getSettings();
$opacity = $this
->getFieldSetting('opacity');
foreach ($items as $delta => $item) {
$color = color_field_hex2rgb($item->color);
if ($opacity) {
$rgbtext = 'rgba(' . $color['r'] . ',' . $color['g'] . ',' . $color['b'] . ',' . $item->opacity . ')';
}
else {
$rgbtext = 'rgb(' . $color['r'] . ',' . $color['g'] . ',' . $color['b'] . ')';
}
$elements[$delta] = array(
'#markup' => '<div style="background-color: ' . $rgbtext . '; width: ' . $settings['width'] . 'px; height: ' . $settings['height'] . 'px;"></div>',
);
}
return $elements;
}
}