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 🙂

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 🙁