Reading list Switch to dark mode

    Restrict Add To Cart According To Condition In Magento 2

    Updated 16 July 2021

    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="" 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" />

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

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

    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 🙂

    Searching for an experienced
    Magento Company ?
    Find out More
    . . .

    Leave a Comment

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


  • Jancy
    I am using magento 2.1.8.
    I have checked the controller_action_predispatch_checkout_cart_add event.
    But in my case,this is not fire 🙁
  • Back to Top

    Message Sent!

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

    Back to Home