You are here

public function DownloadLinkFieldFormatter::viewElements in Media Entity Download 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/DownloadLinkFieldFormatter.php \Drupal\media_entity_download\Plugin\Field\FieldFormatter\DownloadLinkFieldFormatter::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 LinkFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/DownloadLinkFieldFormatter.php, line 37

Class

DownloadLinkFieldFormatter
Plugin implementation of the 'media_entity_download_download_link' formatter.

Namespace

Drupal\media_entity_download\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $parent = $items
    ->getParent()
    ->getValue()
    ->id();
  foreach ($items as $delta => $item) {
    $route_parameters = [
      'media' => $parent,
    ];
    if ($delta > 0) {
      $route_parameters['query']['delta'] = $delta;
    }
    $url = Url::fromRoute('media_entity_download.download', $route_parameters);

    // @todo: replace with DI when this issue is fixed: https://www.drupal.org/node/2053415
    $filename = \Drupal::entityTypeManager()
      ->getStorage('file')
      ->load($item
      ->getValue()['target_id'])
      ->getFilename();
    $elements[$delta] = [
      '#type' => 'link',
      '#url' => $url,
      '#title' => $filename,
    ];
  }
  return $elements;
}