You are here

public function PriceCalculatedFormatter::viewElements in Price 2.0.x

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 PriceDefaultFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/PriceCalculatedFormatter.php, line 96

Class

PriceCalculatedFormatter
Plugin implementation of the 'price_calculated' formatter.

Namespace

Drupal\price\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  if (!$items
    ->isEmpty()) {
    $context = new Context($this->currentUser, NULL, [
      'field_name' => $items
        ->getName(),
    ]);

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $items
      ->getEntity();
    $resolved_price = $this->chainPriceResolver
      ->resolve($entity, 1, $context);
    $number = $resolved_price
      ->getNumber();
    $currency_code = $resolved_price
      ->getCurrencyCode();
    $options = $this
      ->getFormattingOptions();
    $elements[0] = [
      '#theme' => 'price_calculated',
      '#calculated_price' => $this->currencyFormatter
        ->format($number, $currency_code, $options),
      '#entity' => $entity,
      '#cache' => [
        'tags' => $entity
          ->getCacheTags(),
        'contexts' => Cache::mergeContexts($entity
          ->getCacheContexts(), [
          'languages:' . LanguageInterface::TYPE_INTERFACE,
          'country',
        ]),
      ],
    ];
  }
  return $elements;
}