FractionFormatterBase.php in Fraction 8
File
src/Plugin/Field/FieldFormatter/FractionFormatterBase.php
View source
<?php
namespace Drupal\fraction\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class FractionFormatterBase extends FormatterBase implements ContainerFactoryPluginInterface {
public static function defaultSettings() {
return [
'prefix_suffix' => FALSE,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['prefix_suffix'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Display prefix and suffix'),
'#default_value' => $this
->getSetting('prefix_suffix'),
'#weight' => 10,
];
return $elements;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this
->getSetting('prefix_suffix')) {
$summary[] = $this
->t('Display with prefix and suffix.');
}
return $summary;
}
protected function viewOutput(FieldItemInterface $item, $output = '') {
$field_settings = $this
->getFieldSettings();
if ($this
->getSetting('prefix_suffix')) {
$prefixes = isset($field_settings['prefix']) ? array_map([
'Drupal\\Core\\Field\\FieldFilteredMarkup',
'create',
], explode('|', $field_settings['prefix'])) : [
'',
];
$suffixes = isset($field_settings['suffix']) ? array_map([
'Drupal\\Core\\Field\\FieldFilteredMarkup',
'create',
], explode('|', $field_settings['suffix'])) : [
'',
];
$prefix = count($prefixes) > 1 ? $this
->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0];
$suffix = count($suffixes) > 1 ? $this
->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0];
$output = $prefix . $output . $suffix;
}
return $output;
}
}