You are here

public function MediaThumbnailFormatter::viewElements in Media entity 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/MediaThumbnailFormatter.php, line 128

Class

MediaThumbnailFormatter
Plugin implementation of the 'media_thumbnail' formatter.

Namespace

Drupal\media_entity\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $media = $this
    ->getEntitiesToView($items, $langcode);

  // Early opt-out if the field is empty.
  if (empty($media)) {
    return $elements;
  }
  $url = NULL;
  $image_link_setting = $this
    ->getSetting('image_link');

  // Check if the formatter involves a link.
  if ($image_link_setting == 'content') {
    $entity = $items
      ->getEntity();
    if (!$entity
      ->isNew()) {
      $url = $entity
        ->toUrl();
    }
  }
  elseif ($image_link_setting == 'media') {
    $link_media = TRUE;
  }
  $image_style_setting = $this
    ->getSetting('image_style');

  /** @var \Drupal\media_entity\MediaInterface $media_item */
  foreach ($media as $delta => $media_item) {
    if (isset($link_media)) {
      $url = $media_item
        ->toUrl();
    }
    $elements[$delta] = [
      '#theme' => 'image_formatter',
      '#item' => $media_item
        ->get('thumbnail'),
      '#item_attributes' => [],
      '#image_style' => $image_style_setting,
      '#url' => $url,
    ];

    // Collect cache tags to be added for each item in the field.
    $this->renderer
      ->addCacheableDependency($elements[$delta], $media_item);
  }

  // Collect cache tags related to the image style setting.
  $image_style = $this->imageStyleStorage
    ->load($image_style_setting);
  $this->renderer
    ->addCacheableDependency($elements, $image_style);
  return $elements;
}