public function BundlePriceCalculatedFormatter::viewElements in Commerce Product Bundle 8
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 PriceCalculatedFormatter::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ BundlePriceCalculatedFormatter.php, line 28
Class
- BundlePriceCalculatedFormatter
- Plugin implementation of the 'commerce_price_calculated' formatter.
Namespace
Drupal\commerce_product_bundle\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
/** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
$purchasable_entity = $items
->getEntity();
// We only handle product bundles. Let the commerce core calculated price
// formatter handle other purchasable entities.
if (!$purchasable_entity
->getEntityType()
->entityClassImplements(BundleInterface::class)) {
return parent::viewElements($items, $langcode);
}
$context = new Context($this->currentUser, $this->currentStore
->getStore(), NULL, [
'field_name' => $items
->getName(),
]);
// We need to run the logic, even if we have no valid price from the bundle
// entity itself. The bundle price resolver will calculate a price from the
// product bundle items.
for ($delta = $items
->isEmpty() ? 0 : 1; $delta <= count($items); $delta = $delta + 1) {
$resolved_price = $this->chainPriceResolver
->resolve($purchasable_entity, 1, $context);
if ($resolved_price) {
$number = $resolved_price
->getNumber();
$currency_code = $resolved_price
->getCurrencyCode();
$options = $this
->getFormattingOptions();
$elements[$delta] = [
'#markup' => $this->currencyFormatter
->format($number, $currency_code, $options),
'#cache' => [
'tags' => $purchasable_entity
->getCacheTags(),
'contexts' => Cache::mergeContexts($purchasable_entity
->getCacheContexts(), [
'languages:' . LanguageInterface::TYPE_INTERFACE,
'country',
]),
],
];
}
}
return $elements;
}