Home » Magento, Magento 218 July 2016

Magento 2: Event Observer

This article shows how you can create event observer in a custom module in Magento 2.

In Magento 2, there is a separate xml file where you can define your event observer. For frontend events, you need to write your code in app/code/YourCompany/YourModule/etc/frontend/events.xml and for admin events, you need to write event observer code in app/code/YourCompany/YourModule/etc/adminhtml/events.xml.

Remember that, you need to place your Observer class in app/code/YourCompany/YourModule/Observer/ directory.

In the following example, we will be observing the event checkout_onepage_controller_success_action. This event is dispatched when the order is placed and we go to the checkout success page. You can get the list of all the events dispatched in Magento 2 from here: List of all dispatched events in Magento 2.

Here, I suppose that your module is named YourCompany_YourModule.

Let’s first create the events.xml file. This is our frontend events as the event is dispatched on checkout success page in frontend.

app/code/YourCompany/YourModule/etc/frontend/events.xml

Here,

name = unique observer name
instance = full class name of the observer
disabled = enable/disable observer (default value is false)

In the above events.xml code, we have defined Observer class as HelloWorld. Below is the Observer class code. Our code should be in execute function of the HelloWorld class.

app/code/YourCompany/YourModule/Observer/HelloWorld

Read more about Magento 2 Events and Observers in the Official Magento doc: Magento 2 Events and Observers.

Hope this helps.
Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed