5

i created an observer before add to cart like this:

<?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="controller_action_predispatch_checkout_cart_add">
        <observer name="test_custom_controller_action_predispatch_checkout_cart_add" instance="Test\Custom\Observer\BeforeAddCart" />
    </event>
</config>

in this observer i want to check if the cart is empty and do some function, before add product to the cart

1
  • Accept the answer If you find it helpful @Hunter
    – Keyur Shah
    Aug 23 '17 at 11:13
10

You can also use the cart helper

 protected $cartHelper;

 public function __construct(     
        \Magento\Checkout\Helper\Cart $cartHelper
    ) {
        $this->cartHelper = $cartHelper;
    }

and then you can do the check

   if ($this->cartHelper->getItemsCount() === 0) {
          //add your functionality
   }
1

You can get item count using below way,

<?php
namespace Test\Custom\Observer;

use Magento\Framework\Event\ObserverInterface;

class BeforeAddCart implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {        
        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item = $observer->getEvent()->getQuoteItem();
        echo count($item);exit;
    }
}
1
  • You are too fast :) @Rakesh
    – Keyur Shah
    Aug 21 '17 at 7:24
1
protected $_cart;      

public function __construct(     
    \Magento\Checkout\Model\Cart $_cart
) {
    $this->_cart = $_cart;
}

Now you can use this like,

$quote=$this->_cart->getQuote();
$totalItems=count($quote->getAllItems());
if($totalItems==0){
    // do your stuff here
 }

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.