function BaseFieldFileFormatterBase::viewElements

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

Overrides FormatterInterface::viewElements

File

core/modules/file/src/Plugin/Field/FieldFormatter/BaseFieldFileFormatterBase.php, line 93

Class

BaseFieldFileFormatterBase
Base class for file formatters, which allow to link to the file download URL.

Namespace

Drupal\file\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $url = NULL;
    // Add support to link to the entity itself.
    if ($this->getSetting('link_to_file')) {
        $url = $this->fileUrlGenerator
            ->generate($items->getEntity()
            ->getFileUri());
    }
    foreach ($items as $delta => $item) {
        $view_value = $this->viewValue($item);
        if ($url) {
            $elements[$delta] = [
                '#type' => 'link',
                '#title' => $view_value,
                '#url' => $url,
            ];
        }
        else {
            $elements[$delta] = is_array($view_value) ? $view_value : [
                '#markup' => $view_value,
            ];
        }
    }
    return $elements;
}

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