6

In Drupal 8, like Drupal 7, you can enable the file description in the file field setting.

But once my file entity is loaded in my preprocess, I don't know how can I get the description value entered for my file. I've tried (without success) :

$myfileentity->toArray();
$myfileentity->get('description');
$myfileentity->get('description_field');
$myfileentity->label();

Any Idea ?

Thanks.

11

The description is stored on the file field, not on the file entity. To access it, use $node->yourfilefield->description.

  • Cool, that's working even though it seems odd, I think there should be a function like getDescription(). Also I added a solution for multiple field which was my case. – pbonnefoi Sep 28 '16 at 13:08
  • Entity field properties don't have methods, it is always properties, which is actually powered by magic __get()/__set() and so on methods. Multi-value is then just $entity->yourfield[1]->description. – Berdir Sep 29 '16 at 8:10
1

If the field has multiple files you can get the description like so:

$values = $field->getValue();
foreach($values as $value){
   $descriptions[] = $value['description'];
}

Tested in Drupal 8.4.

0

If you want to get the value of the field 'description' you can use something like this:

$fid = 1; //Your file id
$file = \Drupal\file\Entity\File::load($fid);
$file->get('filename')->value; //here to get the file name

To get the list, try dpm(file->toArray());

You can check this pages to know about files and fields.

  • 1
    That gives me the 'filename' like 'mypdf.pdf' where I need the description I put into the field like 'Test PDF'. I ended up making a direct query into the database to get the description stored in node__field_pdf. I'm up for a better solution. – pbonnefoi Sep 28 '16 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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