1

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:

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Url;

<?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.

1

That's right, normally you find the values from the field in $items[$delta].

To make this easier for field formatters getEntitiesToView() puts the item in the returned array. You find the item in _referringItem:

$item = $file->_referringItem;
$description =  $item->description;

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.