function MediaThumbnailFormatter::viewElements

Same name in other branches
  1. 9 core/modules/media/src/Plugin/Field/FieldFormatter/MediaThumbnailFormatter.php \Drupal\media\Plugin\Field\FieldFormatter\MediaThumbnailFormatter::viewElements()
  2. 8.9.x core/modules/media/src/Plugin/Field/FieldFormatter/MediaThumbnailFormatter.php \Drupal\media\Plugin\Field\FieldFormatter\MediaThumbnailFormatter::viewElements()
  3. 11.x core/modules/media/src/Plugin/Field/FieldFormatter/MediaThumbnailFormatter.php \Drupal\media\Plugin\Field\FieldFormatter\MediaThumbnailFormatter::viewElements()

Overrides ImageFormatter::viewElements

File

core/modules/media/src/Plugin/Field/FieldFormatter/MediaThumbnailFormatter.php, line 133

Class

MediaThumbnailFormatter
Plugin implementation of the 'media_thumbnail' formatter.

Namespace

Drupal\media\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $media_items = $this->getEntitiesToView($items, $langcode);
    // Early opt-out if the field is empty.
    if (empty($media_items)) {
        return $elements;
    }
    $image_style_setting = $this->getSetting('image_style');
    
    /** @var \Drupal\media\MediaInterface[] $media_items */
    foreach ($media_items as $delta => $media) {
        $elements[$delta] = [
            '#theme' => 'image_formatter',
            '#item' => $media->get('thumbnail')
                ->first(),
            '#item_attributes' => [
                'loading' => $this->getSetting('image_loading')['attribute'],
            ],
            '#image_style' => $this->getSetting('image_style'),
            '#url' => $this->getMediaThumbnailUrl($media, $items->getEntity()),
        ];
        // Add cacheability of each item in the field.
        $this->renderer
            ->addCacheableDependency($elements[$delta], $media);
    }
    // Add cacheability of the image style setting.
    if ($this->getSetting('image_link') && ($image_style = $this->imageStyleStorage
        ->load($image_style_setting))) {
        $this->renderer
            ->addCacheableDependency($elements, $image_style);
    }
    return $elements;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.