Question

I want to add the double quantity when I click add to cart button using event in Magento2.3.2

which function I can override for this.

Thanks in advance.

Was it helpful?

Solution

Here we will see how to set double Quantity of product in magento2. You can change product quantity when adding product to cart. You can achieve this by Observer.

First create events.xml file in folder ‘Webkul/Hello/etc/frontend’ and use event ‘checkout_cart_product_add_after’.

<?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="customprice" instance="VendorName\ModuleName\Observer\CustomQty" />
    </event>
</config>

Now create CustomQty.php file in Observer folder.

<?php
    namespace VendorName\ModuleName\Observer;

    use Magento\Framework\Event\ObserverInterface;
    use Magento\Framework\App\RequestInterface;

    class CustomQty implements ObserverInterface
    {
        public function execute(\Magento\Framework\Event\Observer $observer) {
            $item = $observer->getEvent()->getData('quote_item');           
            $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
            $qty= $item->getQty() * 2; //set your quantity here
            $item->setQty($qty);
            $item->getProduct()->setIsSuperMode(true);
        }

    }

For cart page or minicart you have to override Magento\Checkout\Controller\Cart\UpdateItemQty controller file through plugin or preference you can see this link how to override controller

https://www.mageplaza.com/magento-2-module-development/magento-2-how-to-rewrite-controller.html

in your overridden controller file replace updateItemQuantity function to

private function updateItemQuantity(Item $item, float $qty)
    {
        if ($qty > 0) {
            $item->clearMessage();
            $item->setQty($qty * 2);

            if ($item->getHasError()) {
                throw new LocalizedException(__($item->getMessage()));
            }
        }
    }

OTHER TIPS

You can create observer to update quantity in cart items.

public function execute(Observer $observer)
{

    $cart = $observer->getData('cart');
    $quote = $cart->getData('quote');
    $items = $quote->getAllVisibleItems();

    foreach($items as $item)
    {   
            $item->setQty(2);
            $item->save();   
    }
    $quote->save();
}

Check this out for details.

Hope this works for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top