You are here

public function FileMediaFormatterBase::viewElements in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase::viewElements()
  2. 9 core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase::viewElements()

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 FormatterInterface::viewElements

File

core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php, line 114

Class

FileMediaFormatterBase
Base class for media file formatter.

Namespace

Drupal\file\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $source_files = $this
    ->getSourceFiles($items, $langcode);
  if (empty($source_files)) {
    return $elements;
  }
  $attributes = $this
    ->prepareAttributes();
  foreach ($source_files as $delta => $files) {
    $elements[$delta] = [
      '#theme' => $this
        ->getPluginId(),
      '#attributes' => $attributes,
      '#files' => $files,
      '#cache' => [
        'tags' => [],
      ],
    ];
    $cache_tags = [];
    foreach ($files as $file) {
      $cache_tags = Cache::mergeTags($cache_tags, $file['file']
        ->getCacheTags());
    }
    $elements[$delta]['#cache']['tags'] = $cache_tags;
  }
  return $elements;
}