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.



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.


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

Hope this helps.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • magento

  • Vivek Shingala

    Hello Mukesh

    Thanks for the post.

    Could you please tell why have you used ->getOrderIds(); instead of ->getOrderId();? I am confused as success action will only generate a single order id.

    Please suggest.

  • getOrderIds() is used because multiple orders are created if you do Multiple Address Checkout in Magento. For Single Address Checkout (the default one), only one order is created.