Same name and namespace in other branches
- 8.x-1.x src/Plugin/Field/FieldFormatter/ColorboxFormatter.php \Drupal\colorbox\Plugin\Field\FieldFormatter\ColorboxFormatter::viewElements() 1 comment
File
-
src/
Plugin/ Field/ FieldFormatter/ ColorboxFormatter.php, line 380
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);
$dompurify = $this->libraryDiscovery
->getLibraryByName('colorbox', 'dompurify');
$dompurify_file = !empty($dompurify['js'][0]['data']) ? DRUPAL_ROOT . '/' . $dompurify['js'][0]['data'] : NULL;
$dompurify_exists = !empty($dompurify) && !empty($dompurify_file) && file_exists($dompurify_file);
if ($dompurify_exists) {
$elements['#attached']['library'][] = 'colorbox/dompurify';
}
}
return $elements;
}