BaseFieldFileFormatterBase.php in Drupal 8
File
core/modules/file/src/Plugin/Field/FieldFormatter/BaseFieldFileFormatterBase.php
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\Form\FormStateInterface;
use Drupal\Core\Url;
abstract class BaseFieldFileFormatterBase extends FormatterBase {
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 = file_create_url($items
->getEntity()->uri->value);
}
foreach ($items as $delta => $item) {
$view_value = $this
->viewValue($item);
if ($url) {
$elements[$delta] = [
'#type' => 'link',
'#title' => $view_value,
'#url' => Url::fromUri($url),
'#cache' => [
'contexts' => [
'url.site',
],
],
];
}
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';
}
}