Version 1
[yaffs-website] / web / core / modules / file / src / Plugin / Field / FieldFormatter / GenericFileFormatter.php
1 <?php
2
3 namespace Drupal\file\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldItemListInterface;
6
7 /**
8  * Plugin implementation of the 'file_default' formatter.
9  *
10  * @FieldFormatter(
11  *   id = "file_default",
12  *   label = @Translation("Generic file"),
13  *   field_types = {
14  *     "file"
15  *   }
16  * )
17  */
18 class GenericFileFormatter extends FileFormatterBase {
19
20   /**
21    * {@inheritdoc}
22    */
23   public function viewElements(FieldItemListInterface $items, $langcode) {
24     $elements = [];
25
26     foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
27       $item = $file->_referringItem;
28       $elements[$delta] = [
29         '#theme' => 'file_link',
30         '#file' => $file,
31         '#description' => $item->description,
32         '#cache' => [
33           'tags' => $file->getCacheTags(),
34         ],
35       ];
36       // Pass field item attributes to the theme function.
37       if (isset($item->_attributes)) {
38         $elements[$delta] += ['#attributes' => []];
39         $elements[$delta]['#attributes'] += $item->_attributes;
40         // Unset field item attributes since they have been included in the
41         // formatter output and should not be rendered in the field template.
42         unset($item->_attributes);
43       }
44     }
45
46     return $elements;
47   }
48
49 }