I want to limit cart items to be added in cart. Limit Checkout Order or Add to Cart Limit to allow only 6 type of items. These 6 items can have variable Qty value.
I have done the below code using Event/Observer but not working.
etc/events.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="ishaq_limit_items_in_cart_checkout_before" instance="Ishaq\LimitCartItems\Observer\Checkout\Cart\Add" />
</event>
</config>
Observer/Checkout/Cart/Add.php
<?php
namespace Ishaq\LimitCartItems\Observer\Checkout\Cart;
use Magento\Checkout\Model\Session;
use Magento\Framework\App\ActionFlag;
use Magento\Framework\App\Response\RedirectInterface as ResponseRedirect;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface as MessageManager;
class Add implements ObserverInterface
{
/** @var Session $session */
private $session;
/** @var ActionFlag $flag */
private $flag;
/** @var ResponseRedirect $redirect */
private $redirect;
/** @var MessageManager $messageManager */
private $messageManager;
/**
* Add constructor.
*
* @param Session $session
* @param ActionFlag $flag
* @param ResponseRedirect $redirect
* @param MessageManager $messageManager
*/
public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Magento\Checkout\Model\Cart $cart,
ResponseRedirect $redirect,
MessageManager $messageManager
) {
$this->_request = $request;
$this->_cart = $cart;
$this->redirect = $redirect;
$this->messageManager = $messageManager;
}
/**
* @param Observer $observer
*
* @return $this|void
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function execute(Observer $observer)
{
$controller = $observer->getControllerAction();
$postValues = $this->_request->getPostValue();
$cartQuote = $this->_cart->getQuote()->getData();
$cartItemsCount = $this->_cart->getQuote()->getItemsCount();
$cartItemsAll = $this->_cart->getQuote()->getAllItems();
if($cartItemsCount > 6)
{
$observer->getRequest()->setParam('product', false);
$observer->getRequest()->setParam('return_url', $this->redirect->getRefererUrl());
$observer->getRequest()->setParam('backUrl', $this->redirect->getRefererUrl());
$this->messageManager->addErrorMessage(
__('Only 6 types of products per purchase allowed. Please complete this order first and place another order afterwards.')
);
}
}
}