public function FileDownloadFieldFormatter::viewElements in File Download 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/ FileDownloadFieldFormatter.php, line 108
Class
- FileDownloadFieldFormatter
- Plugin annotation @FieldFormatter( id = "file_download_formatter", label = @Translation("File Download"), field_types = { "file", "image" } )
Namespace
Drupal\file_download\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$token_data = [
'user' => \Drupal::currentUser(),
$items
->getEntity()
->getEntityTypeId() => $items
->getEntity(),
];
$settings = $this
->getSettings();
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $file) {
$token_data['file'] = $file;
$item = $file->_referringItem;
switch ($settings['link_title']) {
// This is useful for instance if you are using an icon.
case 'empty':
$title = '';
break;
case 'entity_title':
$entity = $items
->getEntity();
$title = NULL;
if ($entity
->label() != NULL) {
$title = $entity
->label();
}
break;
case 'custom':
$title = \Drupal::token()
->replace($settings['custom_title_text'], $token_data, [
'clear' => TRUE,
]);
break;
case 'description':
$title = $item->description;
break;
// This equates to choosing filename.
default:
// If title has no value then filename is substituted
// See template_preprocess_download_file_link()
$title = NULL;
}
if (empty($title) && $settings['link_title'] !== 'empty') {
// If we explicitly want to have a title but no title was defined yet,
// fallback to the filename.
$title = NULL;
}
$elements[$delta] = [
'#theme' => 'download_file_link',
'#file' => $file,
'#title' => $title,
'#description' => $item->description,
'#cache' => [
'tags' => $file
->getCacheTags(),
],
];
if ($settings['file_size']) {
$elements[$delta]['#size'] = format_size($file
->getSize());
$elements[$delta]['#raw_size'] = $file
->getSize();
}
// 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;
}