Magento 2 Programatically clear all tax and Add custom in Observer
-
14-04-2021 - |
Question
I am customize tax calculation on and adding custom tax.I am doing this using observer:
Magento Version is 2.3.4 ,below code is working fine and adding custom rates but My requirement to add clear all added tax before adding new one.
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_quote_address_collect_totals_after">
<observer name="changeTaxTotal" instance="Vendor\CustomTax\Observer\ChangeTaxTotal"/>
</event>
</config>
and observer file is
<?php
namespace Vendorname\CustomTax\Observer;
use \Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\Event\Observer;
class ChangeTaxTotal implements ObserverInterface
{
public function execute(Observer $observer)
{
/** @var Magento\Quote\Model\Quote\Address\Total */
$total = $observer->getData('total');
$subtotal = $total['subtotal'];
$customTax = ($subtotal * 9)/100;
if (trim($total['shipping_description']) == "Shipping_methode_name") {
------------in this line I want to clear all tax -------
$total->addTotalAmount('tax', $customTax);
}
return $this;
}
}
I want to Clear all added tax before adding my custom rateand also want to add tax title. $total->addTotalAmount('tax', $customTax);
If anyone have idea please share me.
Solution
Please change the code as below and try
From:
if (trim($total['shipping_description']) == "Shipping_methode_name") {
------------in this line I want to clear all tax -------
$total->addTotalAmount('tax', $customTax);
}
To:
if (trim($total['shipping_description']) == "Shipping_methode_name") {
------------in this line I want to clear all tax -------
$total->setTotalAmount('tax', $customTax);
}
OTHER TIPS
Please use below code for change title
if (trim($total['shipping_description']) == "Shipping_methode_name") {
------------in this line I want to clear all tax -------
$total->setTotalAmount('tax', $customTax);
$infos = $total->getFullInfo();
foreach($infos as $key1 => $info) {
foreach($info['rates'] as $key2 => $rate) {
if($rate == 'Tax') {
$infos[$key1]['rates'][$key2]['title'] = 'YOUR CUSTOM TITLE';
}
}
}
$total->setFullInfo($infos);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange