Can I change the taxes on a quote item in magento2 programmatically?
-
14-04-2021 - |
Question
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.
Solution
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];
}
}
OTHER TIPS
Yes, you can change.. You can try out below tricks:
create custom tax rules and rates as per current quote address, this will apply tax rate to each product. Product rate you can calculate and save.
use FPT , you can also customize it.. sales_quote_collect_totals_before use this event to change the fixed product tax value, this will add/change fixed amount to each product.