Ever had the requirement in your Magento 2 store of restricting a customer on purchase quantity? I’m sure you had if you were concerned about cost-effective packaging, delivery, shipping, and stock management.
Today, I’ve come up with a method to restrict quantity update from mini cart in Magento 2. This is helpful when you have set a condition of limiting the order quantity. You can restrict customers to update the quantity in mini cart that violates the limit, and shows a message in the popup with the related restriction information.
Method to Restrict Quantity Update From Mini Cart In Magento 2:
1. Create di.xml file at app\code\Vendor\Extension\etc\frontend
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Checkout\Controller\Sidebar\UpdateItemQty"> <plugin name="quantity_update" type="Vendor\Extension\Observer\UpdateItemQty" sortOrder="10"/> </type> </config>
2. Create UpdateItemQty.php file at app\code\Vendor\Extension\Observer
<?php namespace Vendor\Extension\Observer; use Magento\Checkout\Controller\Sidebar\UpdateItemQty as coreUpdateItemQty; use Vendor\Extension\Helper\Data; use Magento\Framework\Json\Helper\Data as coreData; use Magento\Checkout\Model\Sidebar; use Magento\Catalog\Model\ProductFactory; use Magento\Checkout\Model\Cart; use Magento\Framework\Serialize\SerializerInterface; class UpdateItemQty { protected $helper; protected $jsonHelper; protected $sidebar; protected $quoteItemFactory; protected $productFactory; protected $cart; protected $serializer; public function __construct( Data $helper, coreData $jsonHelper, Sidebar $sidebar, Cart $cart, SerializerInterface $serializer, ProductFactory $productFactory ) { $this->helper = $helper; $this->jsonHelper = $jsonHelper; $this->sidebar = $sidebar; $this->productFactory = $productFactory; $this->serializer = $serializer; $this->cart = $cart; } public function aroundExecute(coreUpdateItemQty $subject, \Closure $proceed) { try { if(your condition){ $errorMsg= 'Error Msg'; return $subject->getResponse()->representJson( $this->jsonHelper->jsonEncode($this->sidebar->getResponseData($errorMsg)) ); } } catch (\Exception $e) { return $subject->getResponse()->representJson( $this->jsonHelper->jsonEncode($this->sidebar->getResponseData($e->getMessage())) ); } return $proceed(); } }
That’s it. You can also show additional data in Magento 2 mini cart to show shipping charge, discount or tax information etc.
Limit the quantity or set any conditions for updating quantity right in the mini cart with the above solution!
Thanks!