You are here

public function TableFormatter::viewElements in File Hash 8

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/TableFormatter.php, line 26

Class

TableFormatter
Plugin implementation of the 'filehash_table' formatter.

Namespace

Drupal\filehash\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  if ($files = $this
    ->getEntitiesToView($items, $langcode)) {
    $names = filehash_names();
    $header = [
      $this
        ->t('Attachment'),
      $this
        ->t('Size'),
      $this
        ->t('@algo hash', [
        '@algo' => $names[$this
          ->getSetting('algo')],
      ]),
    ];
    $rows = [];
    foreach ($files as $file) {
      if (property_exists($file, '_referringItem')) {
        $item = $file->_referringItem;
        $rows[] = [
          [
            'data' => [
              '#theme' => 'file_link',
              '#file' => $file,
              '#description' => $this
                ->getSetting('use_description_as_link_text') ? $item->description : NULL,
              '#cache' => [
                'tags' => $file
                  ->getCacheTags(),
              ],
            ],
          ],
          [
            'data' => format_size(method_exists($file, 'getSize') ? $file
              ->getSize() : 0),
          ],
          [
            'data' => [
              '#markup' => substr(chunk_split(property_exists($file, 'filehash') ? $file->filehash[$this
                ->getSetting('algo')] : '', 1, '<wbr />'), 0, -7),
            ],
          ],
        ];
      }
    }
    $elements[0] = [];
    if (!empty($rows)) {
      $elements[0] = [
        '#theme' => 'table__filehash_formatter_table',
        '#header' => $header,
        '#rows' => $rows,
      ];
    }
  }
  return $elements;
}