1

This is my code:

magento/app/code/UV/Download/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="controller_action_predispatch_checkout_cart_add">
        <observer name="UV_Download_Before" instance="UV\Download\Observer\CartObserver" />
    </event>
</config>

magento/app/code/UV/Download/Observer/CartObserver.php

<?php
namespace UV\Download\Observer;

use Magento\Framework\Event\ObserverInterface;

class CartObserver implements ObserverInterface
{
    public function __construct()
    {

    }

    public function execute(\Magento\Framework\Event\Observer $observer) 
    {
        $product = $observer->getEvent()->getProduct();

    }
}
?>

This observer gets called when someone is clicking "Add to Cart". My goal is to get the product which belongs to the "Add to Cart"-Button.

How can I do that?

Thanks!

1 Answer 1

1

Create events : /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="productCustomprice" instance="UV\Download\Observer\CartObserver" />
    </event>
</config>

Create observer for that event : magento/app/code/UV/Download/Observer/CartObserver.php

<?php

namespace UV\Download\Observer;

use Magento\Framework\Event\ObserverInterface;

class CustomPrice implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $item = $observer->getEvent()->getData('quote_item');
        $item = ($item->getParentItem() ? $item->getParentItem() : $item);

        $product_sku = $item->getProduct()->getSku();
    }
}

In this observer you can get Add to cart product data. Please check it.

I hope this will help you.

2
  • Thanks for the fast reply! $item = $observer->getEvent()->getData('quote_item'); $item is null. Edit: nevermind I made a mistake :) Apr 3, 2018 at 13:13
  • It is still null. Your code doesn't work :/ Apr 3, 2018 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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