ColorFieldTextFormatter.php in Color Field 8
File
src/Plugin/Field/FieldFormatter/ColorFieldTextFormatter.php
View source
<?php
namespace Drupal\color_field\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
class ColorFieldTextFormatter extends FormatterBase {
public static function defaultSettings() {
return array(
'format' => 'hexadecimal',
) + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['format'] = array(
'#type' => 'select',
'#title' => t('Format'),
'#options' => $this
->getColorFormat(),
'#default_value' => $this
->getSetting('format'),
);
return $elements;
}
public function getColorFormat($format = NULL) {
$formats = array();
$formats['hexadecimal'] = $this
->t('Hexadecimal Colors');
$formats['rgb'] = $this
->t('RGB Colors');
$formats['rgba'] = $this
->t('RGBA Colors');
if ($format) {
return $formats[$format];
}
return $formats;
}
public function settingsSummary() {
$summary = array();
$format = $this
->getSetting('format');
$summary[] = t('Format: @format', array(
'@format' => $this
->getColorFormat($format),
));
return $summary;
}
public function viewElements(FieldItemListInterface $items) {
$format = $this
->getSetting('format');
$opacity = $this
->getFieldSetting('opacity');
foreach ($items as $delta => $item) {
switch ($format) {
case 'hexadecimal':
$output = '#' . $item->color;
break;
case 'rgb':
$color = color_field_hex2rgb($item->color);
$output = 'rgb(' . $color['r'] . ',' . $color['g'] . ',' . $color['b'] . ')';
break;
case 'rgba':
$color = color_field_hex2rgb($item->color);
$item->opacity = $opacity ? $item->color : 1;
$output = 'rgb(' . $color['r'] . ',' . $color['g'] . ',' . $color['b'] . ',' . $item->color . ')';
break;
}
$elements[$delta] = array(
'#markup' => $output,
);
}
return $elements;
}
}