Version 1
[yaffs-website] / web / core / modules / file / src / Plugin / Field / FieldFormatter / FileUriFormatter.php
1 <?php
2
3 namespace Drupal\file\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemInterface;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Formatter to render the file URI to its download path.
11  *
12  * @FieldFormatter(
13  *   id = "file_uri",
14  *   label = @Translation("File URI"),
15  *   field_types = {
16  *     "uri"
17  *   }
18  * )
19  */
20 class FileUriFormatter extends BaseFieldFileFormatterBase {
21
22   /**
23    * {@inheritdoc}
24    */
25   public static function defaultSettings() {
26     $settings = parent::defaultSettings();
27
28     $settings['file_download_path'] = FALSE;
29     return $settings;
30   }
31
32   /**
33    * {@inheritdoc}
34    */
35   public function settingsForm(array $form, FormStateInterface $form_state) {
36     $form = parent::settingsForm($form, $form_state);
37
38     $form['file_download_path'] = [
39       '#title' => $this->t('Display the file download URI'),
40       '#type' => 'checkbox',
41       '#default_value' => $this->getSetting('file_download_path'),
42     ];
43
44     return $form;
45   }
46
47   /**
48    * {@inheritdoc}
49    */
50   protected function viewValue(FieldItemInterface $item) {
51     $value = $item->value;
52     if ($this->getSetting('file_download_path')) {
53       // @todo Wrap in file_url_transform_relative(). This is currently
54       // impossible. See BaseFieldFileFormatterBase::viewElements(). Fix in
55       // https://www.drupal.org/node/2646744.
56       $value = file_create_url($value);
57     }
58     return $value;
59   }
60
61   /**
62    * {@inheritdoc}
63    */
64   public static function isApplicable(FieldDefinitionInterface $field_definition) {
65     return parent::isApplicable($field_definition) && $field_definition->getName() === 'uri';
66   }
67
68 }