datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/UrlPlainFormatter.php
src/Plugin/DataField/FieldFormatter/UrlPlainFormatter.php
<?php
namespace Drupal\datafield\Plugin\DataField\FieldFormatter;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\datafield\Plugin\DataFieldFormatterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'file_url_plain' formatter.
*/
#[FieldFormatter(
id: 'file_url_plain',
label: new TranslatableMarkup('URL to file'),
field_types: ['file'],
)]
class UrlPlainFormatter implements DataFieldFormatterInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* Constructs a UrlPlainFormatter object.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param mixed $field_definition
* The definition of the field to which the formatter is associated.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entity type manager.
*/
public function __construct($plugin_id, $plugin_definition, $field_definition, protected EntityTypeManagerInterface $entityTypeManager) {
unset($plugin_id, $plugin_definition, $field_definition);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration,
$container->get('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function viewElements($item, $langcode) {
$fid = $item->value;
if (!is_numeric($item->value)) {
return $item->value;
}
$file = $this->entityTypeManager->getStorage('file')->load($fid);
if (empty($file)) {
return '';
}
return [
'#markup' => $file->createFileUrl(),
'#cache' => ['tags' => $file->getCacheTags()],
];
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return [];
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
return [];
}
}
