You are here

public function PercentageFormatter::viewElements in Fraction 8

Same name and namespace in other branches
  1. 2.x src/Plugin/Field/FieldFormatter/PercentageFormatter.php \Drupal\fraction\Plugin\Field\FieldFormatter\PercentageFormatter::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 FractionDecimalFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/PercentageFormatter.php, line 24

Class

PercentageFormatter
Format fraction as percentage.

Namespace

Drupal\fraction\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];

  // Iterate through the items.
  foreach ($items as $delta => $item) {

    /** @var \Drupal\fraction\Fraction $percentage */
    $percentage = clone $item->fraction;
    $percentage
      ->multiply(Fraction::createFromDecimal('100'));
    $auto_precision = !empty($this
      ->getSetting('auto_precision'));
    $output = $percentage
      ->toDecimal($this
      ->getSetting('precision'), $auto_precision) . '%';
    $elements[$delta] = [
      '#markup' => $this
        ->viewOutput($item, $output),
    ];
  }
  return $elements;
}