Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\my_prices\Plugin\Field\FieldFormatter;
- use Drupal\commerce\Context;
- use Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter;
- use Drupal\Core\Cache\Cache;
- use Drupal\Core\Field\Annotation\FieldFormatter;
- use Drupal\Core\Field\FieldItemListInterface;
- use Drupal\Core\Language\LanguageInterface;
- /**
- * Plugin implementation of the 'commerce_price_calculated' formatter.
- *
- * @FieldFormatter(
- * id = "commerce_price_calculated_discounted",
- * label = @Translation("Calculated discounted"),
- * field_types = {
- * "commerce_price"
- * }
- * )
- */
- class PriceCalculatedDiscountedFormatter extends PriceCalculatedFormatter
- {
- 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);
- $currency_code = $result->getCalculatedPrice()->getCurrencyCode();
- $options = $this->getFormattingOptions();
- $number = $result->getCalculatedPrice()->getNumber();
- $discountedPriceFormatter = $this->currencyFormatter->format($number, $currency_code, $options);
- $price = $purchasable_entity->getPrice()->getNumber();
- $originalPriceFormatter = $this->currencyFormatter->format($price, $currency_code, $options);
- if ($number == $price) {
- $markup = sprintf('%s', $discountedPriceFormatter);
- } else {
- $markup = sprintf('<span class="product-price-sale">%s</span> <span class="product-price-base"><del>%s</del></span>', $discountedPriceFormatter, $originalPriceFormatter);
- }
- $elements[0] = [
- '#markup' => $markup,
- '#cache' => [
- 'tags' => $purchasable_entity->getCacheTags(),
- 'contexts' => Cache::mergeContexts($purchasable_entity->getCacheContexts(), [
- 'languages:' . LanguageInterface::TYPE_INTERFACE,
- 'country',
- ]),
- ],
- ];
- }
- return $elements;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement