Magneto Event before customer login to clear carts for logged out customers

Here the art will be updated with custom pricing for the customer when the customer logged in.

With the help of a observer it can be done:-

The event used to trigger the Observer will be :-

controller_action_predispatch_customer_account_loginPost

Observer will contain the repository of Quote,Customer section and cart.

 public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/customerlogged.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info("Before logged in");
        $quotes = $this->checkoutSession->getQuote();
        $items = $quotes->getAllVisibleItems();
        if (count($items) > 0) {
            foreach ($items as $cartItem) {
                $itemId = $cartItem->getItemId();
                $logger->info($itemId);
                $this->cart->removeItem($itemId)->save();
            }
        }

    }
events.xml



    <event name="controller_action_predispatch_customer_account_loginPost">
        <observer name="customer_login" instance="JJ\Customer\Observer\Customerlogin" />
    </event>

Leave a comment

Your email address will not be published. Required fields are marked *