public function EntityReferenceLabelClassFormatter::viewElements in Element Class Formatter 8
Builds a renderable array for a field value.
Parameters
\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.
string $langcode: The language that should be used to render the field.
Return value
array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.
Overrides EntityReferenceLabelFormatter::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ EntityReferenceLabelClassFormatter.php, line 84
Class
- EntityReferenceLabelClassFormatter
- Plugin implementation of the 'file with class' formatter.
Namespace
Drupal\element_class_formatter\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = parent::viewElements($items, $langcode);
$class = $this
->getSetting('class');
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $item) {
// If it's a link add the class.
if (isset($elements[$delta]['#type']) && $elements[$delta]['#type'] === 'link') {
if (!empty($class)) {
$elements[$delta]['#options']['attributes']['class'][] = $class;
}
}
else {
// Otherwise render as a div.
$attributes = new Attribute();
if (!empty($class)) {
$attributes
->addClass($class);
}
// Otherwise collect the info needed for new render.
$label = $elements[$delta]['#plain_text'];
$cache = $elements[$delta]['#cache'];
$elements[$delta] = [
'#type' => 'html_tag',
'#tag' => $this
->getSetting('tag'),
'#attributes' => $attributes
->toArray(),
'#value' => $label,
'#cache' => $cache,
];
}
}
return $elements;
}