0

I have a store which contains only downloadable products.

I'd like to prevent the same product from being added in quantities greater than 1 and remove the quantity field from everywhere (cart, minicart, etc).

I tried to use a Plugin in my module but it doesn't work.

app/code/Vendor/Module/etc/di.xml

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <!-- Frontend --> <type name="Magento\Checkout\Model\Cart"> <plugin disabled="false" name="Vendor_Module_Plugin_Magento_Checkout_Cart_BeforeAddToCart" type="Vendor\Module\Plugin\Magento\Checkout\Cart\BeforeAddToCart"/> </type> </config> 

app/code/Vendor/Module/Plugin/Magento/Checkout/Cart/BeforeAddToCart.php

<?php declare(strict_types=1); namespace Vendor\Module\Plugin\Magento\Checkout\Cart; use Magento\Checkout\Model\Cart; use Magento\Checkout\Helper\Cart as CartHelper; use Magento\Catalog\Model\Product; use Magento\Checkout\Model\Session\Proxy as SessionProxy; use Magento\Framework\Message\ManagerInterface; use Magento\ConfigurableProduct\Model\Product\Type\Configurable; use Magento\Store\Model\StoreManagerInterface; use Magento\Checkout\Model\Session; use Magento\Framework\UrlInterface; class BeforeAddToCart { public function beforeAddProduct(\Magento\Checkout\Model\Cart $subject, $productInfo, $requestInfo=null){ $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $session = $objectManager->create('\Magento\Checkout\Model\Session'); $product_id = $requestInfo['product']; $quote = $session->getQuote()->hasProductId($product_id); if($quote){ // redirect to cart $this->session->setRedirectUrl($this->url->getUrl('checkout/cart/index')); throw new \Magento\Framework\Exception\LocalizedException( __("[x] This product is already in the cart. Testing, testing : ". $product->getSku()) ); } return [$productInfo, $requestInfo]; } } 
4
  • What issue you are facing into above code? Commented Jul 30, 2024 at 10:56
  • @DhirenVasoya I don't want throw an exception with the message. I just wish the product quantity doesn't increase. Commented Jul 30, 2024 at 13:26
  • Then you can always 1 qty pass here, so it always added product with that qty only. Commented Jul 30, 2024 at 13:37
  • What do you mean? If I remove the exception and add $requestInfo['qty'] = 1;, it doesn't work. Commented Jul 30, 2024 at 13:53

4 Answers 4

1

Done using an Observer. Honestly, I don't know if this is achievable through Plugin.

etc/frontend/events.xml

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="checkout_cart_product_add_after"> <observer name="cart_update_custom" instance="Vendor\Module\Observer\UpdateCartItem" /> </event> </config> 

Observer/UpdateCartItem.php

<?php namespace Vendor\Module\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Checkout\Model\Cart; class UpdateCartItem implements ObserverInterface { /** * @var Cart */ protected $_cart; public function __construct( cart $cart ) { $this->_cart = $cart; } /** * After cart observer * @param Observer $observer * @return Cart * @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function execute(Observer $observer) { $quoteItem = $observer->getEvent()->getQuoteItem(); $quoteItem->setData('qty', 1); $this->_cart->save(); } } 
0

Plese update your plugin to this

<?php declare(strict_types=1); namespace Vendor\Module\Plugin\Magento\Checkout\Cart; use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\UrlInterface; use Magento\Catalog\Api\ProductRepositoryInterface; class BeforeAddToCart { protected $session; protected $url; protected $messageManager; protected $productRepository; public function __construct( Session $session, UrlInterface $url, ManagerInterface $messageManager, ProductRepositoryInterface $productRepository ) { $this->session = $session; $this->url = $url; $this->messageManager = $messageManager; $this->productRepository = $productRepository; } public function beforeAddProduct(Cart $subject, $productInfo, $requestInfo = null) { $productId = $requestInfo['product'] ?? null; if ($productId) { $quote = $this->session->getQuote(); foreach ($quote->getAllItems() as $item) { if ($item->getProductId() == $productId) { try { $product = $this->productRepository->getById($productId); $sku = $product->getSku(); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $sku = 'unknown'; //in case the product is not found } $this->session->setRedirectUrl($this->url->getUrl('checkout/cart')); throw new LocalizedException(__("The product with SKU '%1' is already in the cart.", $sku)); } } } return [$productInfo, $requestInfo]; } } 

with result

enter image description here

1
  • Thanks but how can I remove the message having the same result? Because, if I remove the exception throw new LocalizedException(__("The product with SKU '%1' is already in the cart.", $sku)); it doesn't work anymore. Commented Jul 29, 2024 at 9:28
0

You can archive this By this way as well.

Step 1: From the admin panel, move to Stores > Settings > Configuration.

Step 2 : From the left menu, expand CATALOG and choose the Inventory option.

Step 3 : Enlarge the Product Stock Options and set the number of quantities in the Maximum Qty Allowed in Shopping Cart field. (HERE You need to set 1 only)

Step 4 : At last, hit the Save Config button to apply the changes in the storefront.

2
  • Thanks but doing that way you cannot limit the quantity per product. Furthermore, it still shows the error message. Commented Jul 31, 2024 at 8:47
  • Same you can set par product as well, there is product level setting for the same as well. By doing this you do not want to hide qty box on any place, because that will handel by magento it self. Commented Jul 31, 2024 at 8:50
0

@KaMZaTa

Hey,

In Admin Configuration setting:

Store -> Configuration -> Catalog -> Inventory -> Product Stock Options -> Maximum Qty Allowed in Shopping Cart 1

This will allow only 1 qty in cart so you need not to do any coding.

Further you can try with coding, use event/observer - controller_action_predispatch_checkout_cart_add

Thank You!

2
  • Please stop ignoring the posting guidelines. The taglines do not belong on posts here. Commented Aug 2, 2024 at 13:29
  • Thanks but doing that way you still see the popup message. Commented Aug 2, 2024 at 22:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.