I want to Limit Checkout Order or Add to Cart Limit to allow only 6 types of products/items. These 6 items can have variable Qty value. Eg: One Checkout/AddCart Maximum 6 Items: Item-1 25Qty, Item-2 125Qty, Item-3 Sample, Item-4 50Qty, Item-5 100Qty, Item-6 Sample,
So for I have created an extension using Event Observer but it is not working.
code of Vendor/Module/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="limit_items_in_cart_checkout_before" instance="Vendor\Module\Observer\Checkout\Cart\Add" />
</event>
</config>
code of Vendor/Module/Observer/Checkout/Cart/Add.php
<?php
namespace Vendor\Module\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(
Session $session,
ActionFlag $flag,
ResponseRedirect $redirect,
MessageManager $messageManager
) {
$this->session = $session;
$this->flag = $flag;
$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)
{
$quote = $this->session->getQuote();
$itemsCount = $quote->getItemsCount();
if ($itemsCount > 6) {
$request = $observer->getRequest();
$request->setParams([
'product' => false,
'return_url' => $this->redirect->getRefererUrl(),
'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.')
);
$action = $observer->getEvent()->getControllerAction();
$this->flag->set('', \Magento\Framework\App\ActionInterface::FLAG_NO_DISPATCH, true);
$action->getResponse()->setRedirect('/checkout/cart');
return $this;
}
}
}