2

I need to change the tax rate on quote items in a magento2 checkout process that is entirely done programmatically.

What I've found from various resources here on stackoverflow is that is possible to change the quote item's product tax rate

$item->getProduct()->setTaxClassId(1);

In my quote, however, I have many quote items, but they are the all the same catalog-product, only with differrent options aplied to them. Now, when I set the products tax rate like shown above, the last tax-class-id I set is used for ALL items in the quote.

I need a way to set the tax on the quote item directly. But

$item->setTaxPercent(4)

(e.g.) has no effect.

0

That's how you should do it:

Change the file app/code/Vendor/Package/etc/di.xml in your custom package by adding the line

<type name="Magento\Checkout\Model\Cart">
    <plugin name="interceptAddingProductToCart" type="Vendor\Package\Model\Checkout\Cart\Plugin" sortOrder="10" disabled="false"/>
</type>

Create the plugin

app/code/Vendor/Package/Model/Checkout/Cart/Plugin.php

Now, add the content to the file above:

<?php

namespace Vendor\Package\Model\Checkout\Cart;

class Plugin
{
    /**
     * @var \Magento\Quote\Model\Quote
     */
    protected $quote;

    /**
     * Plugin constructor.
     *
     * @param \Magento\Checkout\Model\Session $checkoutSession
     */
    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->quote = $checkoutSession->getQuote();
    }

    public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
    {
        # Do something, here for instance, it remove TAX for giftvouchers
        if ($productInfo->getTypeId() == 'giftvoucher') {
            $productInfo->setTaxClassId(0);
        }

        return [$productInfo, $requestInfo];
    }
}
  • hi @medina, can we set fixed tax price for product when added to cart? – jafar pinjar May 14 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.