:::: MENU ::::

Magento 2 event observer

Magento 2 event observer

Today we talk about how in Magento 2 event observer. This tutorial included observing event sales_order_save_commit_after. Following this example you can observe any event in magento 2. So let start with our example.

Create event.xml

First create the events.xml in QaisarSatti/HelloWorld/etc/events.xml. If you want to observe the event that trigger only the frontend you create events.xml file QaisarSatti/HelloWorld/etc/frontend/events.xml. Same as you want to observe the events that trigger in admin side create file QaisarSatti/HelloWorld/etc/adminhtml/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="sales_order_save_commit_after">
        <observer name="helloworld_sales_order_save_after" instance="QaisarSatti\HelloWorld\Observer\Observer" />

Create Observer.php

Now we create Observer.php in following directory QaisarSatti\HelloWorld\Observer. Inject \Magento\Framework\Event\Observer in your method to get event data.

namespace QaisarSatti\HelloWorld\Observer;
use Magento\Framework\Event\ObserverInterface;
class Observer implements ObserverInterface {
  public function execute(\Magento\Framework\Event\Observer $observer) {
                 $order = $observer->getEvent()->getOrder(); //get order information      
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


  • Reply Viki patel |

    Can we apply the same principle for a customer from front end ? I mean when he gets logs in can we apply the same principle to perform certain operations?

So, what do you think ?