FileUriFormatter.php 1.72 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
<?php

/**
 * @file
 * Contains \Drupal\file\Plugin\Field\FieldFormatter\FileUriFormatter.
 */

namespace Drupal\file\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Formatter to render the file URI to its download path.
 *
 * @FieldFormatter(
 *   id = "file_uri",
 *   label = @Translation("File URI"),
 *   field_types = {
 *     "uri"
 *   }
 * )
 */
class FileUriFormatter extends BaseFieldFileFormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = parent::defaultSettings();

    $settings['file_download_path'] = FALSE;
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);

    $form['file_download_path'] = [
      '#title' => $this->t('Display the file download URI'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('file_download_path'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function viewValue(FieldItemInterface $item) {
    $value = $item->value;
    if ($this->getSetting('file_download_path')) {
58 59 60
      // @todo Wrap in file_url_transform_relative(). This is currently
      // impossible. See BaseFieldFileFormatterBase::viewElements(). Fix in
      // https://www.drupal.org/node/2646744.
61 62 63 64 65 66 67 68 69 70 71 72 73
      $value = file_create_url($value);
    }
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return parent::isApplicable($field_definition) && $field_definition->getName() === 'uri';
  }

}