You are here

public function NumericFormatterBase::viewElements in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/NumericFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\NumericFormatterBase::viewElements()
  2. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/NumericFormatterBase.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\NumericFormatterBase::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/NumericFormatterBase.php, line 61

Class

NumericFormatterBase
Parent plugin for decimal and integer formatters.

Namespace

Drupal\Core\Field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $settings = $this
    ->getFieldSettings();
  foreach ($items as $delta => $item) {
    $output = $this
      ->numberFormat($item->value);

    // Account for prefix and suffix.
    if ($this
      ->getSetting('prefix_suffix')) {
      $prefixes = isset($settings['prefix']) ? array_map([
        'Drupal\\Core\\Field\\FieldFilteredMarkup',
        'create',
      ], explode('|', $settings['prefix'])) : [
        '',
      ];
      $suffixes = isset($settings['suffix']) ? array_map([
        'Drupal\\Core\\Field\\FieldFilteredMarkup',
        'create',
      ], explode('|', $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;
    }

    // Output the raw value in a content attribute if the text of the HTML
    // element differs from the raw value (for example when a prefix is used).
    if (isset($item->_attributes) && $item->value != $output) {
      $item->_attributes += [
        'content' => $item->value,
      ];
    }
    $elements[$delta] = [
      '#markup' => $output,
    ];
  }
  return $elements;
}