View source
<?php
namespace Drupal\cshs\Plugin\Field\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CshsFlexibleHierarchyFormatter extends CshsFormatterBase {
protected $token;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->token = $container
->get('token');
return $instance;
}
public static function defaultSettings() : array {
$settings = parent::defaultSettings();
$settings['format'] = '[term:name]';
$settings['clear'] = TRUE;
return $settings;
}
public function settingsForm(array $form, FormStateInterface $form_state) : array {
$element = parent::settingsForm($form, $form_state);
$element['format'] = [
'#type' => 'textfield',
'#title' => $this
->t('Format'),
'#description' => $this
->t('Specify a format for each field item by using tokens.'),
'#default_value' => $this
->getSetting('format'),
];
$element['clear'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Clear Tokens'),
'#description' => $this
->t('Remove token from final text if no replacement value is generated'),
'#default_value' => $this
->getSetting('clear'),
];
if (\Drupal::moduleHandler()
->moduleExists('token')) {
$element['token_help'] = [
'#type' => 'markup',
'#theme' => 'token_tree_link',
'#token_types' => [
'term',
],
];
}
return $element;
}
public function settingsSummary() : array {
$summary = parent::settingsSummary();
$summary[] = $this
->t('Format: @format', [
'@format' => $this
->getSetting('format'),
]);
return $summary;
}
public function viewElements(FieldItemListInterface $items, $langcode) : array {
$elements = [];
$linked = $this
->getSetting('linked');
$format = $this
->getSetting('format');
$clear = $this
->getSetting('clear');
foreach ($this
->getEntitiesToView($items, $langcode) as $delta => $term) {
$text = $this->token
->replace($format, [
'term' => $term,
], [
'clear' => $clear,
]);
$elements[$delta]['#markup'] = $linked ? $term
->toLink($text)
->toString() : $text;
}
return $elements;
}
}