3 namespace Drupal\file\Plugin\Field\FieldFormatter;
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemInterface;
7 use Drupal\Core\Field\FieldItemListInterface;
8 use Drupal\Core\Field\FormatterBase;
9 use Drupal\Core\Form\FormStateInterface;
13 * Base class for file formatters, which allow to link to the file download URL.
15 abstract class BaseFieldFileFormatterBase extends FormatterBase {
20 public static function defaultSettings() {
21 $settings['link_to_file'] = FALSE;
29 public function settingsForm(array $form, FormStateInterface $form_state) {
30 $form = parent::settingsForm($form, $form_state);
32 $form['link_to_file'] = [
33 '#title' => $this->t('Link this field to the file download URL'),
34 '#type' => 'checkbox',
35 '#default_value' => $this->getSetting('link_to_file'),
44 public function viewElements(FieldItemListInterface $items, $langcode) {
48 // Add support to link to the entity itself.
49 if ($this->getSetting('link_to_file')) {
50 // @todo Wrap in file_url_transform_relative(). This is currently
51 // impossible. See below.
52 $url = file_create_url($items->getEntity()->uri->value);
55 foreach ($items as $delta => $item) {
56 $view_value = $this->viewValue($item);
61 '#title' => $view_value,
62 '#url' => Url::fromUri($url),
63 // @todo Remove the 'url.site' cache context by using a relative file
64 // URL (file_url_transform_relative()). This is currently impossible
65 // because #type => link requires a Url object, and Url objects do not
66 // support relative URLs: they require fully qualified URLs. Fix in
67 // https://www.drupal.org/node/2646744.
76 $elements[$delta] = is_array($view_value) ? $view_value : ['#markup' => $view_value];
84 * Generate the output appropriate for one field item.
86 * @param \Drupal\Core\Field\FieldItemInterface $item
90 * The textual output generated.
92 abstract protected function viewValue(FieldItemInterface $item);
97 public static function isApplicable(FieldDefinitionInterface $field_definition) {
98 return $field_definition->getTargetEntityTypeId() === 'file';