skip to Main Content

I want to track the Magento shop data by hooks the Magento events. I’m new in Magento2 so I don’t know to hook the events and where to call an observer. I want to know how to call events which directory can we called. what hierarchy can be used? How to know the name of events?

2

Answers


  1. Very basic information about the events and observers you can find in the manual, check here: https://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html

    Login or Signup to reply.
  2. Create a event file: events.xml

    File: app/code/Vendor_Name/Module_Name/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_add_product_complete">
            <observer name="observername" instance="Vendor_NameModule_NameObserverObserverClass" />
        </event>
    </config>
    

    Create Observer class

    File: app/code/Vendor_Name/Module_Name/Observer/ObserverClass.php

    <?php
    
    namespace Vendor_NameModule_NameObserver;
    
    class ObserverClass implements MagentoFrameworkEventObserverInterface
    {
        public function execute(MagentoFrameworkEventObserver $observer)
        {
            //Your code to run when event is fired.
            return 'Event fired';
        }
    }
    

    In above example, whenever event “checkout_cart_add_product_complete” is fired, the code inside Observer class will be executed.

    To get a list of events available in Magento 2, you can visit : Link

    Thanks, I hope this will help you. If you have any doubt or problem, feel free to ask in comment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search