How can you display document file sizes next to a media link button?

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 = [

  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 %}

One Answer

function HOOK_preprocess_file_link(&$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileSize' => $variables['file']
      'fileSizeFormatted' => format_size($variables['file']

{{ 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

Field Formatter File Size is a field formatter to display the file size.

Answered by Yuseferi on November 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP