Drupal Answers Asked by Paul H on November 13, 2020
I’m trying to display the file size of a file next to a media link button on a page.
I have two content types with a media entity reference field in each. Each field is restricted to only pull from a file media type. What I was trying to do was create a twig variable using a field preprocess and pop that variable inside each of my field templates. However, my preprocess below doesn’t seem to be displaying the file size as I want. What am I doing wrong?
function theme_preprocess_field(&$variables, $hook) {
$pdf_fields = [
'field_1',
'field_2'
];
if (in_array($element['#field_name'], $pdf_fields) && $element['#entity_type'] == 'node') {
if ($variables['items'][0]) {
$field_name = $element['#field_name'];
$node = $element['#object'];
// Get first referenced media id.
$media_id = $node->$field_name->target_id;
// Get file object.
$file = DrupalfileEntityFile::load($media_id);
if ($file) {
// Get file size.
$file_size = format_size($file->getSize());
// Set file size variable.
$variables['file_size'] = $file_size;
}
}
}
}
Twig field template
{% for item in items %}
<a href="{{ item.content['#url'] }}" class="button">Download Paper</a><span>(PDF | {{ file_size }})</span>
{% endfor %}
function HOOK_preprocess_file_link(&$variables) {
if (isset($variables['file'])) {
$variables['fileLinkDisplay'] = [
'fileSize' => $variables['file']
->getSize(),
'fileSizeFormatted' => format_size($variables['file']
->getSize()),
];
}
}
{{ fileLinkDisplay.fileSize }}
and {{ fileLinkDisplay.fileSizeFormatted }}
will be available in your template.
PS: if it works then you can more filter to restrict to the content type and field you want applied for.
Additionally, there is a module that show the size https://www.drupal.org/project/field_formatter_file_size
Field Formatter File Size is a field formatter to display the file size.
Answered by Yuseferi on November 13, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP