public function BaseFieldFileFormatterBase::viewElements in Drupal 10
Same name and namespace in other branches
- 8 core/modules/file/src/Plugin/Field/FieldFormatter/BaseFieldFileFormatterBase.php \Drupal\file\Plugin\Field\FieldFormatter\BaseFieldFileFormatterBase::viewElements()
- 9 core/modules/file/src/Plugin/Field/FieldFormatter/BaseFieldFileFormatterBase.php \Drupal\file\Plugin\Field\FieldFormatter\BaseFieldFileFormatterBase::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/ 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\FieldFormatterCode
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;
}