#StackBounty: #magento2 #event-observer #product-attribute #tax Apply Tax to the cart total based on product attribute value magento 2.3

Bounty: 50

I am applying custom tax for the cart item based on the product attribute value.

used below event for that.

Vendor/Module/etc/events.xml

<event name="sales_quote_address_collect_totals_after">
    <observer name="changeTax" instance="VendorModuleObserverChangeTax"/>
</event>

Then VendorModuleObserverChangeTax.php

<?php
namespace VendorModuleObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
class ChangeTax implements ObserverInterface
{
 private $logger;
 protected $_productloader;
 protected $_cart;
 public function __construct(
     PsrLogLoggerInterface $logger,
     MagentoCatalogModelProductFactory $_productloader,
     MagentoCheckoutModelCart $cart
  ) {
     $this->logger = $logger;
     $this->_productloader = $_productloader;       
     $this->_cart = $cart;      
   }
 public function execute(Observer $observer)
  {
    /** @var MagentoQuoteModelQuoteAddressTotal */
     $this->logger->info('--total--');
     $total = $observer->getData('total');
     // retrieve quote items collection     
     $itemsCollection = $this->_cart->getQuote()->getItemsCollection();
     $isDeliverable = [];
     foreach($itemsCollection as $items){
        $productId = $items->getProductId();
        $this->logger->info('--itemIds--'.$productId);
        $product = $this->_productloader->create()->load($productId);
        $deliveryProduct = $product->getIsDelivery();
        if($deliveryProduct){
            $isDeliverable[] = $productId;
         }          
       }
      if(count($isDeliverable) > 0){
        $this->logger->info('--inside--');
        $total->addBaseTotalAmount('tax', 6);
        $total->setGrandTotal((float)$total->getGrandTotal() + 6);
        $total->setBaseGrandTotal((float)$total->getBaseGrandTotal() + 6);
      }
      return $this;
   }
}

The event is firing but the Tax is not getting applied, can anyone help me on this issue please? Thank you for the support!!


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.