You are here

public function PriceCalculatedFormatter::viewElements in Commerce Core 8.2

Same name in this branch
  1. 8.2 modules/price/src/Plugin/Field/FieldFormatter/PriceCalculatedFormatter.php \Drupal\commerce_price\Plugin\Field\FieldFormatter\PriceCalculatedFormatter::viewElements()
  2. 8.2 modules/order/src/Plugin/Field/FieldFormatter/PriceCalculatedFormatter.php \Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter::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 PriceDefaultFormatter::viewElements

File

modules/order/src/Plugin/Field/FieldFormatter/PriceCalculatedFormatter.php, line 162

Class

PriceCalculatedFormatter
Alternative implementation of the 'commerce_price_calculated' formatter.

Namespace

Drupal\commerce_order\Plugin\Field\FieldFormatter

Code

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

    /** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
    $purchasable_entity = $items
      ->getEntity();
    $adjustment_types = array_filter($this
      ->getSetting('adjustment_types'));
    $result = $this->priceCalculator
      ->calculate($purchasable_entity, 1, $context, $adjustment_types);
    $calculated_price = $result
      ->getCalculatedPrice();
    $options = $this
      ->getFormattingOptions();
    $elements[0] = [
      '#theme' => 'commerce_price_calculated',
      '#result' => $result,
      '#calculated_price' => $this->currencyFormatter
        ->format($calculated_price
        ->getNumber(), $calculated_price
        ->getCurrencyCode(), $options),
      '#base_price' => $this->currencyFormatter
        ->format($result
        ->getBasePrice()
        ->getNumber(), $calculated_price
        ->getCurrencyCode(), $options),
      '#adjustments' => $result
        ->getAdjustments(),
      '#purchasable_entity' => $purchasable_entity,
      '#cache' => [
        'tags' => $purchasable_entity
          ->getCacheTags(),
        'contexts' => Cache::mergeContexts($purchasable_entity
          ->getCacheContexts(), [
          'languages:' . LanguageInterface::TYPE_INTERFACE,
          'country',
        ]),
      ],
    ];
  }
  return $elements;
}