Magento2 – Add Event After User Adds Product to Cart to Update Quantity

event-observermagento-2.1magento2magento2.2

I am beginner in magento 2 and I am trying to create an event and observer that will update the qty of item to 2 from default which is 1 when user add the item to cart. For this I successfully created the module and registered it and event file is as below

app/code/My/Redirect/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="after_add_to_cart" instance="My\Redirect\Observer\MyObserver" />
    </event>
</config>

and observer as below
app/code/My/Redirect/Observer/MyObserver.php

<?php

namespace My\Redirect\Observer;

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

class MyObserver implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) {
        $item = $observer->getEvent()->getData('quote_item');
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
        $price = 100; //set your price here
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }

}

here the program is changing the price to 100 in base currency and its working fine but i want to update the qty with price according to that qty.

Best Answer

You can check list of all events in Magento 2 version from, List of Magento 2 Events.

You need to use events checkout_cart_update_items_before or checkout_cart_update_items_after to accomplish your task,

Now you need to create an events.xml file,

<?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_update_items_before">
        <observer name="after_add_to_cart" instance="My\Redirect\Observer\MyObserver" />
    </event>
</config>

Create observer and do the logic for your events.