function ColorBackgroudFormatter::viewElements
Same name in other branches
- 8.x-1.x field_example/src/Plugin/Field/FieldFormatter/ColorBackgroudFormatter.php \Drupal\field_example\Plugin\Field\FieldFormatter\ColorBackgroudFormatter::viewElements()
- 4.0.x modules/field_example/src/Plugin/Field/FieldFormatter/ColorBackgroudFormatter.php \Drupal\field_example\Plugin\Field\FieldFormatter\ColorBackgroudFormatter::viewElements()
Overrides FormatterInterface::viewElements
File
-
modules/
field_example/ src/ Plugin/ Field/ FieldFormatter/ ColorBackgroudFormatter.php, line 31
Class
- ColorBackgroudFormatter
- Plugin implementation of the 'field_example_color_background' formatter.
Namespace
Drupal\field_example\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
// Set the value of the CSS color property depending on user provided
// configuration. Individual configuration items can be accessed with
// $this->getSetting('key') where 'key' is the same as the key in the
// form array from settingsForm() and what's defined in the configuration
// schema.
$text_color = 'inherit';
if ($this->getSetting('adjust_text_color')) {
$text_color = $this->lightness($item->value) < 50 ? 'white' : 'black';
}
$elements[$delta] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $this->t('The content area color has been changed to @code', [
'@code' => $item->value,
]),
'#attributes' => [
'style' => 'background-color: ' . $item->value . '; color: ' . $text_color,
],
];
}
return $elements;
}