Magento – Magento 2 How to Update current cart subtotal and grand Total

magento2

Hello please help me to sorted out the issue

I need to update Grand Total and Subtotal of the current cart using observer in magento 2 please let me know how to do this!!!

I need cart item price total in Grand Total and Subtotal please give me step by step execution!!!

Best Answer

Some Minor Correction is Required, Please Try below code

First add the event.xml file in your module

Directory Path: app/code/Vendor/Module/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
   <event name="checkout_cart_product_add_after">
       <observer name="checkout_cart_product_add_after" instance="Vendor\Module\Observer\CheckoutCartAddObserver" />
   </event>
</config>

Then add observer file : app/code/Vendor/Module/Observer/CheckoutCartAddObserver.php

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CheckoutCartAddObserver implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
  {

     $item = $observer->getEvent()->getQuoteItem();
     $item->getQuote()->collectTotals();
     $customSubtotal = 100; //You can set your custom subtotal amount
     $customGrandTotal = 200; //You can set your custom Grand total amount
     $updatedSubtotal = $item->getQuote()->setSubtotal($customSubtotal); 
     $updatedGrandTotal = $item->getQuote()->setGrandTotal($customGrandTotal);               
   }
}

After code change run below command

1) php bin/magento setup:upgrade
2) php bin/magento setup:static-content:deploy -f
3) php bin/magento indexer:reindex
4) php bin/magento cache:flush