1

I'm trying to display the format and size of a file attached to an article. Its system name is field_file.

So far, I've succeeded to load an article in my my_theme.theme file and the field_file field attached to it:

$article = Node::load($article_nid); $variables['file'] = $article->get('field_file');

then use its uri in a twig file: {{file_url(file.entity.fileuri)}}

Now I'm trying to display its format and size. I tried {{file.entity.format}} and {{file.entity.filesize}} without success.

Does anyone have a clue how to do it? I'm still new to Drupal plugins and entities.

1 Answer 1

3

Try getSize and getMimeType in your my_theme.theme as in the example below

function my_theme_preprocess_node(&$vars) {
  $node = $vars['node'];
  $type = $node->getType();
  if( $type == "article" && $node->hasField('field_file')){
      //next gets FieldItemList
      //$file = $node->get('field_file');  

      //you need get the file entity
      $file = $node->get('field_file')->entity;
      $vars["size"] = $file->getSize();
      $vars["type"] = $file->getMimeType();     
  }
}
3
  • Thanks for your answer, I already tried the first method, but since my field is a FieldItemList field and not a type File field (no idea why), it doesn't work
    – Améziane
    Feb 18, 2018 at 21:00
  • $node->get('field_file')->entity will give you the entity, look at example above
    – GiorgosK
    Feb 19, 2018 at 6:48
  • Do you then display the file type of field 'field_file' using this in the twig file: {{type}} Nov 3, 2019 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.