Magento Asked by Lokesh Naik on December 15, 2020
I want a feature where if a customer tries to add a product which already exists in cart then it should prevent it from adding again or qty increase. Instead I want to show a message that ‘The product already exists in cart’.
This is for product types simple, custom options and configurable options.
Any idea how can this be achieved?
Note: We do allow increase qty but only on cart page and that depends upon some specific set of conditions. The only thing we need here is to prevent qty increase when the same product is added from catalog, category or search page.
You can set it by Magento 2 configuration :
Store -> Configuration -> Catalog -> Inventory -> Product Stock Options -> Maximum Qty Allowed in Shopping Cart
Step 1 -
Create events.xml :
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="vendor_model_cart_add_before" instance="VendorModuleObserverCartAddBefore" />
</event>
Step 2 -
Create CartAddBefore.php :
<?php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkAppObjectManager;
class CartAddBefore implements ObserverInterface {
protected $_cart;
protected $_messageManager;
protected $_request;
public function __construct(
MagentoCheckoutModelCart $cart,
MagentoFrameworkMessageManagerInterface $messageManager,
MagentoFrameworkAppRequestInterface $request,
) {
$this->_cart = $cart;
$this->_messageManager = $messageManager;
$this->_request = $request;
}
public function execute(MagentoFrameworkEventObserver $observer) {
$postValues = $this->_request->getPostValue();
$cartItemsCount = $this->_cart->getQuote()->getItemsCount();
if($cartItemsCount > 1)
{
...... your logic .......
$this->_messageManager->addError(__('Sorry, Only 1 product is allowed'));
}
}
}
Answered by Hamendra Sunthwal on December 15, 2020
You can do that with default Magento setup.
In Magento Admin, go to
For all Products
Stores > Configuration > Catalog > Inventory > Product Stock Options.
For individual Product
Catalog > Click on Product from Grid > Advanced Inventory
Set Maximum Qty Allowed in Shopping Cart
to 1. This will restrict allowing more than 1 item in the shopping cart.
Hope it was helpful. Thanks.
Answered by Abdul Pathan on December 15, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP