You are here

public function FileDownloadLinkFormatter::viewElements in Commerce File 8.2

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

src/Plugin/Field/FieldFormatter/FileDownloadLinkFormatter.php, line 24

Class

FileDownloadLinkFormatter
Plugin implementation of the 'commerce_file_download_link' formatter.

Namespace

Drupal\commerce_file\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];

  // This is very similar to the "file_default" formatter provided by
  // the core file module, except that it outputs a url to our file download
  // route.
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $file) {
    $item = $file->_referringItem;
    $elements[$delta] = [
      '#theme' => 'commerce_file_download_link',
      '#file' => $file,
      '#description' => $this
        ->getSetting('use_description_as_link_text') ? $item->description : NULL,
      '#cache' => [
        'tags' => $file
          ->getCacheTags(),
      ],
    ];

    // Pass field item attributes to the theme function.
    if (isset($item->_attributes)) {
      $elements[$delta] += [
        '#attributes' => [],
      ];
      $elements[$delta]['#attributes'] += $item->_attributes;

      // Unset field item attributes since they have been included in the
      // formatter output and should not be rendered in the field template.
      unset($item->_attributes);
    }
  }
  return $elements;
}