0

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.

0

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="Vendor\Module\Observer\CartAddBefore" />
</event>

Step 2 -
Create CartAddBefore.php :

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;

class CartAddBefore implements ObserverInterface {

    protected $_cart;
    protected $_messageManager;
    protected $_request;


    public function __construct(
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\RequestInterface $request,
    ) {
        $this->_cart = $cart;
        $this->_messageManager = $messageManager;
        $this->_request = $request;        
    }

    public function execute(\Magento\Framework\Event\Observer $observer) {

        $postValues = $this->_request->getPostValue();
        $cartItemsCount = $this->_cart->getQuote()->getItemsCount();

        if($cartItemsCount > 1)
        {
            ...... your logic .......
            $this->_messageManager->addError(__('Sorry, Only 1 product is allowed'));
        }
    }
}
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.