Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Restrict Add To Cart According To Condition In Magento 2

Here we learn how to restrict ‘Add To Cart’ according to condition in Magento 2

For this i’ll use controller_action_predispatch_checkout_cart_add observer

1=> We create events.xml file in app/code/NameSpace/ModuleName/etc/frontend location and add following 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="controller_action_predispatch_checkout_cart_add">
        <observer name="yourcustomname" instance="NameSpace\ModuleName\Observer\RestrictAddToCart" />
    </event>
</config>

2=> Now we create your class where we check condition and restrict Add To Cart

Create RestrictAddToCart.php file at NameSpace\ModuleName\Observer\ location

<?php
namespace NameSpace\ModuleName\Observer;
 
use Magento\Framework\Event\ObserverInterface;
 
class RestrictAddToCart implements ObserverInterface
{
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $_messageManager;
 
    /**
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     */
    public function __construct(
        \Magento\Framework\Message\ManagerInterface $messageManager
    )
    {
        $this->_messageManager = $messageManager;
    }
 
    /**
     * add to cart event handler.
     *
     * @param \Magento\Framework\Event\Observer $observer
     *
     * @return $this
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if (/* your condition */) {
                $this->_messageManager->addError(__('your custom message'));
                //set false if you not want to add product to cart
                $observer->getRequest()->setParam('product', false);
                return $this;
         }
 
        return $this;
    }
}

now flush your magento2 cache and it will working on your magento2 website.
after click add to cart button 1st it check condition and proceed according to condition
Thanks 🙂

. . .

Leave a Comment

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


1 comments

  • Jancy
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home