public function PanopolyMediaResponsiveThumbnail::viewElements in Panopoly 8.2
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 MediaThumbnailFormatter::viewElements
File
- modules/
panopoly/ panopoly_media/ src/ Plugin/ Field/ FieldFormatter/ PanopolyMediaResponsiveThumbnail.php, line 164
Class
- PanopolyMediaResponsiveThumbnail
- Plugin implementation of the 'Responsive thumbnail' formatter.
Namespace
Drupal\panopoly_media\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
/** @var \Drupal\media\MediaInterface[] $media_items */
$media_items = $this
->getEntitiesToView($items, $langcode);
// Early opt-out if the field is empty.
if (empty($media_items)) {
return $elements;
}
// Collect cache tags to be added for each item in the field.
$responsive_image_style = $this->responsiveImageStyleStorage
->load($this
->getSetting('responsive_image_style'));
$image_styles_to_load = [];
$cache_tags = [];
if ($responsive_image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $responsive_image_style
->getCacheTags());
$image_styles_to_load = $responsive_image_style
->getImageStyleIds();
}
$image_styles = $this->imageStyleStorage
->loadMultiple($image_styles_to_load);
foreach ($image_styles as $image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $image_style
->getCacheTags());
}
foreach ($media_items as $delta => $media_item) {
$file = $media_item
->get('thumbnail')
->first();
// Extract field item attributes for the theme function, and unset them
// from the $item so that the field template does not re-render them.
$file_attributes = $file->_attributes;
unset($file->_attributes);
$elements[$delta] = [
'#theme' => 'responsive_image_formatter',
'#item' => $file,
'#item_attributes' => $file_attributes,
'#responsive_image_style_id' => $responsive_image_style ? $responsive_image_style
->id() : '',
'#url' => $this
->getMediaThumbnailUrl($media_item, $items
->getEntity()),
'#cache' => [
'tags' => $cache_tags,
],
];
}
return $elements;
}