3

Actually I have made observer as per Below

XML Path:-

app/code/Practice/Observer/etc/frontend/events.xml

XML Code:-

<?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="Practice\Observer\Observer\Alert" />
   </event>
</config>

Observer Path:-

app/code/Practice/Observer/Observer/Alert.php

Observer Code:-

<?php

namespace Practice\Observer\Observer;

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

class Alert implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$item = $observer->getEvent()->getData();         
       print_r($item);
       exit();
}
}

It is working perfectly but i cannot get grandtotal using print_r function.

7

Try following code:

$item = $observer->getEvent()->getQuoteItem();
$item->getQuote()->collectTotals();
$subtotal = $item->getQuote()->getSubtotal();
$grandTotal = $item->getQuote()->getGrandTotal();

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info(array("Subtotal: ".$subtotal, "GrandTotal: ".$grandTotal));
  • I want to show result in print_r() or in echo like print_r($grandTotal); but it is not showing result why? – Jaimin Jan 18 '18 at 7:11
  • @Jaimin - Please check updated answer. – Pratik Oza Jan 18 '18 at 7:23
  • i already tried this but if i put die or exit then product cant add to cart so i cant see the result. – Jaimin Jan 18 '18 at 7:26
  • @Jaimin - You can check with log file, please try updated code. – Pratik Oza Jan 18 '18 at 7:30
  • Done :) @Pratik Oza – Jaimin Jan 18 '18 at 8:17
-3

Try this:

$item = $observer->getEvent()->getQuoteItem();
$item->getQuote()->collectTotals();
$quote = $item->getQuote();
$subTotal = $quote->getSubtotal();
$grandTotal = $quote->getGrandTotal();

 \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')
                ->debug('subTotal', array('subTotal'=> $subTotal));
 \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')
                ->debug('grandTotal', array('grandTotal'=> $grandTotal));

Note: Check your result in var\log

  • Actually i want collection after add to cart but after putting your first code i cant add product to the cart @Abdul – Jaimin Jan 18 '18 at 7:21
  • Pls check ans updated and check your log – Abdul Jan 18 '18 at 7:31
  • Do not use ObjectManager directly in module. – meet Jan 18 '18 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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