View source
<?php
namespace Drupal\field_formatter\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterPluginManager;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Render\Element;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FieldLink extends FieldWrapperBase {
protected $languageManager;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, FormatterPluginManager $formatter_plugin_manager, LanguageManagerInterface $language_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings, $formatter_plugin_manager);
$this->languageManager = $language_manager;
}
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('plugin.manager.field.formatter'), $container
->get('language_manager'));
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$field_output = $this
->getFieldOutput($items, $langcode);
$elements = [];
foreach (Element::children($field_output) as $key) {
$entityUrl = $items
->getEntity()
->toUrl('canonical', [
'language' => $this->languageManager
->getLanguage($langcode),
]);
$elements[$key] = [
'#type' => 'link',
'#url' => $entityUrl,
'#title' => $field_output[$key],
];
}
return $elements;
}
}