FileUrlFormatter.php in File URL 2.0.x
File
src/Plugin/Field/FieldFormatter/FileUrlFormatter.php
View source
<?php
namespace Drupal\file_url\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;
use Drupal\file_url\FileUrlHandler;
class FileUrlFormatter extends FileFormatterBase {
public static function defaultSettings() {
return [
'mode' => 'link',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['mode'] = [
'#type' => 'radios',
'#title' => $this
->t('Mode'),
'#options' => [
'link' => $this
->t('Link (file and extension as link text)'),
'plain' => $this
->t('Plain URL'),
],
'#default_value' => $this
->getSetting('mode'),
];
return $elements;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
switch ($this
->getSetting('mode')) {
case 'link':
$summary[] = $this
->t('Link to file with file name and extension as text');
break;
case 'plain':
$summary[] = $this
->t('Plain URL');
}
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $file) {
$item = $file->_referringItem;
if ($this
->getSetting('mode') === 'plain') {
$elements['delta'] = [
$elements[$delta] = [
'#markup' => file_url_transform_relative(file_create_url($file
->getFileUri())),
'#cache' => [
'tags' => $file
->getCacheTags(),
],
],
];
}
else {
$elements[$delta] = [
'#theme' => 'file_link',
'#file' => $file,
'#description' => $item->description,
'#cache' => [
'tags' => $file
->getCacheTags(),
],
];
}
if (isset($item->_attributes)) {
$elements[$delta] += [
'#attributes' => [],
];
$elements[$delta]['#attributes'] += $item->_attributes;
unset($item->_attributes);
}
$elements[$delta]['#attributes']['title'] = file_create_url($file
->getFileUri());
}
return $elements;
}
public function prepareView(array $entities_items) {
foreach ($entities_items as $items) {
foreach ($items as $item) {
$item->_loaded = FALSE;
if ($this
->needsEntityLoad($item)) {
$file = FileUrlHandler::urlToFile($item->target_id);
$entities[$item->target_id] = $file;
}
}
}
foreach ($entities_items as $items) {
foreach ($items as $item) {
if (isset($entities[$item->target_id])) {
$item->entity = $entities[$item->target_id];
$item->_loaded = TRUE;
}
elseif ($item
->hasNewEntity()) {
$item->_loaded = TRUE;
}
}
}
}
}