0

Once the VAT ID input is filled with a value, an ajax is triggered validating the VAT. In that moment I would like to remove the tax from the checkout and update the totals. I've been trying to do something like this: The code below updates the totals, but does not update the tax to 0.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$checkoutSession = $objectManager->get('Magento\Checkout\Model\Session');
$allItems = $checkoutSession->getQuote()->getAllVisibleItems();
$items = [];
foreach ($allItems as $item) {
   $itemId = $item->getItemId();
   $items[] = [
       'qty' => $item->getQty(),
       'sku' => $item->getSku(),
       'product_id' => $item->getId(),
       'tax' => $item->getTaxAmount(),
       'price' => $item->getBasePrice(),
       'price_inc_vat' => $item->getBasePriceInclTax(),
   ];
   $item->setOriginalCustomPrice($item->getBasePrice());
// $item->setPriceInclTax($item->getBasePrice());
   $item->save();
}
$checkoutSession->getQuote()->collectTotals()->save();

But I'm sure this is not the best approach. Curious how can this be achieved ?

1 Answer 1

0

Using dependency Injections:

use Magento\Tax\Model\TaxClass\Source\Product as ProductTaxClassSource;

/**
 * @var ProductTaxClassSource
 */
protected $productTaxClassSource;


 /**     
 * @param ProductTaxClassSource $productTaxClassSource     
 */
public function __construct(        
    ProductTaxClassSource $productTaxClassSource,        
) {
    
     $this->productTaxClassSource = $productTaxClassSource;

}

Set a value:

$this->getCheckoutSession()->setVarValue('yourValue'); // setTaxValue ('0')

Unset a Value:

$this->getCheckoutSession()->unsVarValue(); // unsTaxValue()

Using Object Manager

$checkoutSession = $objectManager->get('\Magento\Checkout\Model\Session');

if the VAT at checkout is stored in mage_checkout_model_session:

$vat = $checkoutSession->getQuote()->getCustomerTaxvat();
  if($vat):
       $this->setTaxValue(0); // or setCustomerTax(0)
         else:
          {other codes}
       
  endif;

Set a Value:

$checkoutSession->setVarValue('yourValue');  // setCustomerTax or setTaxValue

Unset a Value:

$checkoutSession->unsVarValue();  // unsCustomerTax or unsTaxValue
2
  • Thanks for your post, do you mean $checkoutSession->getQuote()->setCustomerTaxvat(0); instead of $checkoutSession->setVarValue('yourValue'); ? Feb 11, 2022 at 15:42
  • Yes. You can use it if you have B2C and B2B customers. You can first check if the customer has VAT ID or not. If yes? Then set the value to "0". I hope it helps :)
    – Booba
    Feb 11, 2022 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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