3 namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
5 use Drupal\Core\Field\AllowedTagsXssTrait;
6 use Drupal\Core\Field\FormatterBase;
7 use Drupal\Core\Field\FieldItemListInterface;
8 use Drupal\Core\Form\FormStateInterface;
11 * Parent plugin for decimal and integer formatters.
13 abstract class NumericFormatterBase extends FormatterBase {
15 use AllowedTagsXssTrait;
20 public function settingsForm(array $form, FormStateInterface $form_state) {
23 '.' => t('Decimal point'),
26 chr(8201) => t('Thin space'),
27 "'" => t('Apostrophe'),
29 $elements['thousand_separator'] = [
31 '#title' => t('Thousand marker'),
32 '#options' => $options,
33 '#default_value' => $this->getSetting('thousand_separator'),
37 $elements['prefix_suffix'] = [
38 '#type' => 'checkbox',
39 '#title' => t('Display prefix and suffix'),
40 '#default_value' => $this->getSetting('prefix_suffix'),
50 public function settingsSummary() {
53 $summary[] = $this->numberFormat(1234.1234567890);
54 if ($this->getSetting('prefix_suffix')) {
55 $summary[] = t('Display with prefix and suffix.');
64 public function viewElements(FieldItemListInterface $items, $langcode) {
66 $settings = $this->getFieldSettings();
68 foreach ($items as $delta => $item) {
69 $output = $this->numberFormat($item->value);
71 // Account for prefix and suffix.
72 if ($this->getSetting('prefix_suffix')) {
73 $prefixes = isset($settings['prefix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['prefix'])) : [''];
74 $suffixes = isset($settings['suffix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $settings['suffix'])) : [''];
75 $prefix = (count($prefixes) > 1) ? $this->formatPlural($item->value, $prefixes[0], $prefixes[1]) : $prefixes[0];
76 $suffix = (count($suffixes) > 1) ? $this->formatPlural($item->value, $suffixes[0], $suffixes[1]) : $suffixes[0];
77 $output = $prefix . $output . $suffix;
79 // Output the raw value in a content attribute if the text of the HTML
80 // element differs from the raw value (for example when a prefix is used).
81 if (isset($item->_attributes) && $item->value != $output) {
82 $item->_attributes += ['content' => $item->value];
85 $elements[$delta] = ['#markup' => $output];
94 * @param mixed $number
98 * The formatted number.
100 abstract protected function numberFormat($number);