Price with taxes and without taxes on the product page


#1

I need to know any way to show the price with taxes and without taxes on the product page.


#2

Something like that (example code, will not work as is):

<?php

namespace App\Foo;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Product\Resolver\ProductVariantResolverInterface;
use Sylius\Component\Taxation\Calculator\CalculatorInterface;
use Sylius\Component\Taxation\Resolver\TaxRateResolverInterface;

class Foo
{
    /**
     * @var TaxRateResolverInterface
     */
    private $taxRateResolver;

    /**
     * @var CalculatorInterface
     */
    private $calculator;

    /**
     * @var ProductVariantResolverInterface
     */
    private $variantResolver;

    /**
     * @var ChannelInterface
     */
    private $channel;

    /**
     * @param TaxRateResolverInterface $taxRateResolver
     * @param CalculatorInterface $calculator
     * @param ProductVariantResolverInterface $variantResolver
     * @param ChannelInterface $channel
     */
    public function __construct(TaxRateResolverInterface $taxRateResolver, CalculatorInterface $calculator, ProductVariantResolverInterface $variantResolver, ChannelInterface $channel)
    {
        $this->taxRateResolver = $taxRateResolver; // sylius.tax_rate_resolver
        $this->calculator = $calculator; // sylius.tax_calculator
        $this->variantResolver = $variantResolver; // sylius.product_variant_resolver.default
        $this->channel = $channel; // or 'sylius.context.channel' service
    }

    /**
     * @param ProductInterface $product
     *
     * @return array
     */
    public function foo(ProductInterface $product): array
    {
        /** @var ProductVariantInterface $variant */
        $variant = $this->variantResolver->getVariant($product);

        $taxRate = $this->taxRateResolver->resolve($variant);

        $price = $variant->getChannelPricingForChannel($this->channel)->getPrice();

        $totalTaxAmount = $this->calculator->calculate($price, $taxRate);

        if ($taxRate->isIncludedInPrice()) {
            $priceWithTax = $price;
            $priceWithoutTax = $price - $totalTaxAmount;
        } else {
            $priceWithTax = $price + $totalTaxAmount;
            $priceWithoutTax = $price;
        }

        return [$priceWithTax, $priceWithoutTax];
    }
}

#3

Thanks @vvasiloi. Great!