Greetings to all of you.
This is my first question posted around here, so any suggestions are welcome on improving how to better formulate questions.
Into the matter. I have the following code in a Drupal 8 site:
<?php
/**
* @file
* Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\MyModuleFormatter.
*/
namespace Drupal\mymodule\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Url;
/**
* Plugin implementation of the 'mymodule' formatter.
*
* @FieldFormatter(
* id = "mymodule",
* label = @Translation("My Module"),
* field_types = {
* "file"
* }
* )
*/
class MyModuleFormatter extends MyModuleFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = array();
$files = $this->getEntitiesToView($items, $langcode);
/**
* Early opt-out if the field is empty.
*/
if (empty($files)) {
return $elements;
}
foreach ($files as $delta => $file) {
$file_uri = $file->getFileUri();
$elements[$delta] = array(
'#theme' => 'mymodule',
'#files' => array(Url::fromUri(file_create_url($file_uri)));
);
}
return $elements;
}
}
So far so good. Everything is working.
Now, I would like to include in $elements the file description. Something like:
foreach ($files as $delta => $file) {
$file_uri = $file->getFileUri();
$file_description = <someting> // That's what is needed...
$elements[$delta] = array(
'#theme' => 'mymodule',
'#files' => array(Url::fromUri(file_create_url($file_uri)));
'#descriptions' => array($file_description); // ...so it can go here.
);
}
As stated by Berdir, it looks that the description is stored on the file field, not on the file entity. Yes, seems to be there, somewhere in $items.
How to get it?
Many thanks.