Magento2 Frontend – Open Minicart When Item is Added

frontendmagento2mini-cart

I have a relatively stock minicart implementation, and I wanted to know if there is a configuration option or some other way of setting up the mini cart to drop down (open) when an item is successfully added to your cart on the frontend

Current behavior is the item count updates, but the minicart dropdown stays closed. Thanks!

Best Answer

For Magento 2

Pop up minicart when I add a product to the cart magento 2

I'm referring to Open header cart when product added to cart & https://stackoverflow.com/questions/13841390/toggle-dropdown-mini-cart-when-product-added-to-basket which are in Magento 1.

In Magento 2 we can create Event Observer for this

app\code\Custom\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="controller_action_predispatch_checkout_cart_add">
        <observer name="open_mini_cart" instance="Custom\Module\Observer\OpenMiniCartObserver" />
    </event>
</config>

app\code\Custom\Module\Observer\OpenMiniCartObserver.php

namespace Custom\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;

class OpenMiniCartObserver implements ObserverInterface {

    protected $_urlManager;
    protected $redirect;

    public function __construct(
\Magento\Framework\UrlInterface $urlManager, \Magento\Framework\App\Response\RedirectInterface $redirect
) {
        $this->_urlManager = $urlManager;
        $this->redirect = $redirect;
    }

 public function execute(\Magento\Framework\Event\Observer $observer) {

    $actionName = $observer->getEvent()->getRequest()->getFullActionName();
    $controller = $observer->getControllerAction();
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $cartUpdated = $objectManager->get('Magento\Checkout\Model\Session')->getCartWasUpdated(false);

    if ($cartUpdated) {
        // open mini cart
    }
    $this->redirect->redirect($controller->getResponse(), $this->redirect->getRefererUrl());
}

Still Some JS Stuff missing

Related Topic