public function FileDownloadLinkFormatter::viewElements in File Entity (fieldable files) 8.2
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/ FileDownloadLinkFormatter.php, line 142
Class
- FileDownloadLinkFormatter
- Plugin implementation of the 'file_download_link' formatter.
Namespace
Drupal\file_entity\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
// For token replace, we also want to use the parent entity of the file.
$parent_entity = $items
->getParent()
->getValue();
if (!empty($parent_entity)) {
$parent_entity_type = $parent_entity
->getEntityType()
->id();
$token_data[$parent_entity_type] = $parent_entity;
}
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $file) {
// Prepare the attributes for the main container of the template.
$attributes = new Attribute();
// Prepare the text and the URL of the link.
$mime_type = $file
->getMimeType();
$token_data['file'] = $file;
$link_text = $this->token
->replace($this
->getSetting('text'), $token_data);
// Set options as per anchor format described at
// http://microformats.org/wiki/file-format-examples
$download_url = $file
->downloadUrl(array(
'attributes' => array(
'type' => $mime_type . '; length=' . $file
->getSize(),
),
));
if ($file
->access('download')) {
$elements[$delta] = [
'#theme' => 'file_entity_download_link',
'#file' => $file,
'#download_link' => Link::fromTextAndUrl($link_text, $download_url),
'#icon' => file_icon_class($mime_type),
'#attributes' => $attributes,
'#file_size' => format_size($file
->getSize()),
];
}
else {
$elements[$delta] = [
'#markup' => $this
->getSetting('access_message'),
];
}
$this->renderer
->addCacheableDependency($elements[$delta], $file);
}
return $elements;
}