The post shows the solution to restrict customer from adding product to cart in Magento 2.
You may use this solution when you are running an offer where conditions need to be checked for eligibility to avail discounts before the customers place an order. Till then, the admin can restrict customers to add products to the cart or update the cart.
Also, if you are accepting orders based on conditions such as only a particular customer group can place an order, or customers from specific locations can place the order, in these cases, you may restrict them to add the product to the cart until the conditions are checked.
Hence, whenever you want to confirm the order placement request from the backend and only after that allow customer to add another product or update the cart, use the below solution.
Method to Restrict Customer from Adding Product to Cart in Magento 2:
Add code in app\code\vendor\module\etc\di.xml
<type name="Magento\Checkout\Model\Cart"> <plugin name="lock_customer_cart" type="Vendor\Module\Plugin\Lockcart"/> </type>
Create file Lockcart.php under app\code\vendor\module\Plugin\
<?php namespace Vendor\Module\Plugin; use Magento\Framework\Message\ManagerInterface ; use Magento\Checkout\Model\Session; use Magento\Checkout\Model\Cart; class Lockcart { protected $_messageManager; protected $quote; public function __construct( Session $checkoutSession, ManagerInterface $messageManager ) { $this->quote = $checkoutSession->getQuote(); $this->_messageManager = $messageManager; } public function beforeAddProduct( Cart $subject, $productInfo, $requestInfo = null ) { $this->allowedMethod($subject); // you can put custom condition and message here to restrict cart return [$productInfo, $requestInfo]; } public function beforeUpdateItems(Cart $subject, $data) { $this->allowedMethod($subject); // you can put custom condition and message here to restrict cart return [$data]; } public function beforeUpdateItem( Cart $subject, $requestInfo = null, $updatingParams = null ) { $this->allowedMethod($subject); // you can put custom condition and message here to restrict cart return [$requestInfo, $updatingParams]; } public function beforeRemoveItem(Cart $subject, $itemId) { $this->allowedMethod($subject); // you can put custom condition and message here to restrict cart return [$itemId]; } }
That’s it.
Please share the solution with the Magento Community via social media.
Thank you.