datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/EntityReferenceLabelFormatter.php
src/Plugin/DataField/FieldFormatter/EntityReferenceLabelFormatter.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 'entity reference label' formatter.
*/
#[FieldFormatter(
id: 'entity_reference_label',
label: new TranslatableMarkup('Label'),
description: new TranslatableMarkup('Display the label of the referenced entities.'),
field_types: ['entity_reference'],
)]
class EntityReferenceLabelFormatter implements DataFieldFormatterInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* Constructs a UrlPlainFormatter object.
*
* The plugin implementation definition.
*
* @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 static function defaultSettings() {
return [
'link' => TRUE,
];
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$settings = $form['#settings'];
$elements['link'] = [
'#title' => $this->t('Link label to the referenced entity'),
'#type' => 'checkbox',
'#default_value' => $settings['link'] ?? TRUE,
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary($settings = []) {
$summary = [];
$summary[] = !empty($settings['link']) ? $this->t('Link to the referenced entity') : $this->t('No link');
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements($item, $langcode) {
if (empty($item->value)) {
return $item->value;
}
$explode = explode(':', $item->field_setting["entity_reference_type"]);
$reference_type = end($explode);
$entity = $item->value;
if (!empty($item->field_setting["target_bundles"]) && $item->field_setting["target_bundles"] == 'file') {
$reference_type = 'file';
}
if (is_numeric($entity)) {
$entity = $this->entityTypeManager->getStorage($reference_type)
->load($entity);
}
if (empty($entity)) {
return '';
}
$label_field = $entity->getEntityType()->getKey('label');
$title = $label_field ? $entity->get($label_field)?->value : '';
if (empty($title) && method_exists($entity, 'getDisplayName')) {
$title = $entity->getDisplayName();
}
if (!empty($item->settings["link"]) && $entity->hasLinkTemplate('canonical')) {
return [
'#type' => 'link',
'#langcode' => $langcode,
'#title' => $title,
'#url' => $entity->toUrl(),
'#cache' => ['tags' => $entity->getCacheTags()],
];
}
else {
return [
'#plain_text' => $title,
'#langcode' => $langcode,
'#cache' => ['tags' => $entity->getCacheTags()],
];
}
}
}
