public function AutoImageStyleDefault::viewElements in Auto image style 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 ImageFormatter::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ AutoImageStyleDefault.php, line 89
Class
- AutoImageStyleDefault
- Plugin annotation @FieldFormatter( id = "auto_image_style_default", label = @Translation("Image auto orientation"), description = @Translation("Display image fields as portrait or landscape style"), field_types = { "image", } )
Namespace
Drupal\auto_image_style\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$files = $this
->getEntitiesToView($items, $langcode);
// Early opt-out if the field is empty.
if (empty($files)) {
return $elements;
}
// Currently no link handling.
$url = NULL;
$image_style_landscape_setting = $this
->getSetting('image_style_landscape');
$image_style_portrait_setting = $this
->getSetting('image_style_portrait');
// Collect cache tags to be added for each item in the field.
$cache_tags = [];
if (!empty($image_style_landscape_setting)) {
$image_style = $this->imageStyleStorage
->load($image_style_landscape_setting);
$cache_tags_landscape = $image_style
->getCacheTags();
$cache_tags = Cache::mergeTags($cache_tags, $cache_tags_landscape);
}
if (!empty($image_style_portrait_setting)) {
$image_style = $this->imageStyleStorage
->load($image_style_portrait_setting);
$cache_tags_portrait = $image_style
->getCacheTags();
$cache_tags = Cache::mergeTags($cache_tags, $cache_tags_portrait);
}
foreach ($files as $delta => $file) {
$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;
$image_style = $image_style_portrait_setting;
if ($item->height < $item->width) {
$image_style = $image_style_landscape_setting;
}
$item_attributes = $item->_attributes;
unset($item->_attributes);
$elements[$delta] = [
'#theme' => 'image_formatter',
'#item' => $item,
'#item_attributes' => $item_attributes,
'#image_style' => $image_style,
'#url' => $url,
'#cache' => [
'tags' => $cache_tags,
],
];
}
return $elements;
}