View source
<?php
namespace Drupal\field_token_value\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\field_token_value\WrapperManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FieldTokenValueTextFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
protected $wrappers;
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('field_token_value.wrapper_manager'));
}
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, WrapperManagerInterface $wrappers) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->wrappers = $wrappers;
}
public static function defaultSettings() {
return [
'wrapper' => '',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['wrapper'] = [
'#type' => 'select',
'#title' => t('Wrapper'),
'#description' => t('The wrapper to use for the field output.'),
'#default_value' => $this
->getSetting('wrapper'),
'#options' => $this->wrappers
->getWrapperOptions(),
'#empty_option' => t('- Select wrapper -'),
];
return $element;
}
public function settingsSummary() {
$summary = [];
$selected = $this
->getSetting('wrapper');
if (!empty($selected)) {
$wrapper = $this->wrappers
->getDefinition($selected);
$summary[] = $this
->t('Display: @summary', [
'@summary' => $wrapper['summary'],
]);
}
else {
$summary[] = $this
->t('No wrapper has been selected so a paragraph tag will be used by default');
}
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
$selected = $this
->getSetting('wrapper');
if (!empty($items[0])) {
$element[0] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $items[0]->value,
];
if (!empty($selected)) {
$wrapper_info = $this->wrappers
->getDefinition($selected);
$element[0]['#tag'] = $wrapper_info['tag'];
if (isset($wrapper_info['attributes'])) {
$element[0]['#attributes'] = $wrapper_info['attributes'];
}
\Drupal::moduleHandler()
->alter('field_token_value_output', $element[0], $wrapper_info);
}
}
return $element;
}
}