You are here

public function FileMiconFormatter::viewElements in Micon 8

Same name and namespace in other branches
  1. 2.x src/Plugin/Field/FieldFormatter/FileMiconFormatter.php \Drupal\micon\Plugin\Field\FieldFormatter\FileMiconFormatter::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

src/Plugin/Field/FieldFormatter/FileMiconFormatter.php, line 109

Class

FileMiconFormatter
Plugin implementation of the 'file_micon' formatter.

Namespace

Drupal\micon\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $file) {
    $item = $file->_referringItem;
    $url = file_create_url($file
      ->getFileUri());
    $options = [];
    if ($this
      ->getSetting('target')) {
      $options['attributes']['target'] = '_blank';
    }
    $link_text = $this
      ->getSetting('title') ? $this
      ->getSetting('title') : $item->description;
    $position = $this
      ->getSetting('position');
    $icon = $this
      ->mimeMap($file
      ->getMimeType());
    $link_text = micon($link_text)
      ->setIcon($this
      ->mimeMap($file
      ->getMimeType()));
    if ($position == 'after') {
      $link_text
        ->setIconAfter();
    }
    if ($this
      ->getSetting('text_only')) {
      $elements[$delta]['#markup'] = $link_text;
    }
    else {
      $elements[$delta] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options))
        ->toRenderable();
    }
    $elements[$delta]['#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;
}