View source
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class BaseFieldFileFormatterBase extends FormatterBase {
protected $fileUrlGenerator;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, FileUrlGeneratorInterface $file_url_generator = NULL) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
if (!$file_url_generator) {
@trigger_error('Calling BaseFieldFileFormatterBase::__construct() without the $file_url_generator argument is deprecated in drupal:9.3.0 and the $file_url_generator argument will be required in drupal:10.0.0. See https://www.drupal.org/node/2940031', E_USER_DEPRECATED);
$file_url_generator = \Drupal::service('file_url_generator');
}
$this->fileUrlGenerator = $file_url_generator;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
->get('file_url_generator'));
}
public static function defaultSettings() {
$settings['link_to_file'] = FALSE;
return $settings;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['link_to_file'] = [
'#title' => $this
->t('Link this field to the file download URL'),
'#type' => 'checkbox',
'#default_value' => $this
->getSetting('link_to_file'),
];
return $form;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$url = NULL;
if ($this
->getSetting('link_to_file')) {
$url = $this->fileUrlGenerator
->generate($items
->getEntity()
->getFileUri());
}
foreach ($items as $delta => $item) {
$view_value = $this
->viewValue($item);
if ($url) {
$elements[$delta] = [
'#type' => 'link',
'#title' => $view_value,
'#url' => $url,
];
}
else {
$elements[$delta] = is_array($view_value) ? $view_value : [
'#markup' => $view_value,
];
}
}
return $elements;
}
protected abstract function viewValue(FieldItemInterface $item);
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition
->getTargetEntityTypeId() === 'file';
}
}