How to limit quantities added to the cart in Magento 2

Posted on Posted in Magento 2

Often we need to limit the quantities added to cart or say you can only add products with quantity 2,6,9,12 . We can do that by simply using plugin in magento 2.

I am assuming you know how to declare modules in magento 2 we will work on the main part.
di.xml in app/code/Vendor/Modulename/etc

<?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\Model\Cart”>
<plugin name=”CustomCartController” type=”Vendor\Modulename\Plugin\AddPlugin” sortOrder=”10″ />
</type>

</config>

AddPlugin.php in app/code/Vendor/Modulename/Plugin

<?php

namespace Vendor\Modulename\Plugin;

use Magento\Framework\Exception\LocalizedException;

class AddPlugin
{
/**
* @var \Magento\Quote\Model\Quote
*/
protected $quote;

protected $request;

protected $logger;

/**
* Plugin constructor.
*
* @param \Magento\Checkout\Model\Session $checkoutSession
*/
public function __construct(
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Framework\App\Request\Http $request,
\Psr\Log\LoggerInterface $logger
) {
$this->quote = $checkoutSession->getQuote();

$this->request = $request;

$this->logger = $logger;
}

/**
* beforeAddProduct
*
* @param $subject
* @param $productInfo
* @param null $requestInfo
*
* @return array
* @throws LocalizedException
*/
public function beforeAddProduct(\Magento\Checkout\Model\Cart $subject, $productInfo, $requestInfo = null)
{
$productId = (int)$this->request->getParam(‘product’, 0);
$qty = (int)$this->request->getParam(‘qty’, 1);

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get(‘\Magento\Checkout\Model\Cart’);

// get quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();

// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();

// get quote items array
$items = $cart->getQuote()->getAllItems();
$newQty=0;
foreach($items as $item) {
if($item->getProductId()==$productId){
$newQty=$qty+$item->getQty();
}
}

if($newQty>2 && $newQty<16){ throw new LocalizedException(__(‘You can only add quantities 1,2,16 in the Cart!’)); } else if($newQty>16){
throw new LocalizedException(__(‘You cannot add quantities more than 16 in the Cart!’));
}else{

}

return array($productInfo, $requestInfo);
}

public function beforeUpdateItems(\Magento\Framework\DataObject $subject,$data){

foreach ($data as $itemId => $itemInfo) {
if($itemInfo[‘qty’]>2 && $itemInfo[‘qty’]<16){ throw new LocalizedException(__(‘You can only add quantities 1,2,16 in the Cart!’)); }else if($itemInfo[‘qty’]>16){
throw new LocalizedException(__(‘You cannot add quantities more than 16 in the Cart!’));
}else{}
}
return array($data);
}
}

Thats it!!!

Leave a Reply

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