public function ColorboxFormatter::viewElements in Colorbox 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 FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ ColorboxFormatter.php, line 350
Class
- ColorboxFormatter
- Plugin implementation of the 'colorbox' formatter.
Namespace
Drupal\colorbox\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$settings = $this
->getSettings();
$files = $this
->getEntitiesToView($items, $langcode);
// Early opt-out if the field is empty.
if (empty($files)) {
return $elements;
}
// Collect cache tags to be added for each item in the field.
$cache_tags = [];
if (!empty($settings['colorbox_node_style']) && $settings['colorbox_node_style'] != 'hide') {
$image_style = $this->imageStyleStorage
->load($settings['colorbox_node_style']);
$cache_tags = $image_style
->getCacheTags();
}
$cache_tags_first = [];
if (!empty($settings['colorbox_node_style_first'])) {
$image_style_first = $this->imageStyleStorage
->load($settings['colorbox_node_style_first']);
$cache_tags_first = $image_style_first
->getCacheTags();
}
foreach ($files as $delta => $file) {
// Check if first image should have separate image style.
if ($delta == 0 && !empty($settings['colorbox_node_style_first'])) {
$settings['style_first'] = TRUE;
$settings['style_name'] = $settings['colorbox_node_style_first'];
$cache_tags = Cache::mergeTags($cache_tags_first, $file
->getCacheTags());
}
else {
$settings['style_first'] = FALSE;
$settings['style_name'] = $settings['colorbox_node_style'];
$cache_tags = Cache::mergeTags($cache_tags, $file
->getCacheTags());
}
// Extract field item attributes for the theme function, and unset them
// from the $item so that the field template does not re-render them.
$item = $file->_referringItem;
$item_attributes = $item->_attributes;
unset($item->_attributes);
$elements[$delta] = [
'#theme' => 'colorbox_formatter',
'#item' => $item,
'#item_attributes' => $item_attributes,
'#entity' => $items
->getEntity(),
'#settings' => $settings,
'#cache' => [
'tags' => $cache_tags,
],
];
}
// Attach the Colorbox JS and CSS.
if ($this->attachment
->isApplicable()) {
$this->attachment
->attach($elements);
}
return $elements;
}