How to Create Observer in Magento 2?

  • author-img Nidhi Arora
  • 5 years
  • 233 views
How to Create Observer in Magento 2?

Creating an observer in Magento 2 is a bit different from Magento 1.x version. In Magento 2, an observer can be originated from the events.xml file under etc directory.

Let’s have a closer look on how to create observer in Magento 2:

1.  The very first step is to define observer in the file:

<?xml version="1.0"?>
<config>
 <event name="controller_action_catalog_product_save_entity_after">
 <observer name="Envision_Eecom_Product_Save_Later" instance="Envision\Eecom\Observer\productSaveLater" />
 </event>
</config>

Note: Different places are required to make files for different handlers.

• Make file under: app/code/ Envision/Eecom/etc/frontend/event.xml for frontend observer.

• Make file under: app/code/Envision/Eecom/etc/adminhtml/event.xml for frontend observer.

• Generate file under: app/code/Envision/Eecom/etc/event.xml for having observer at both ends.

2. Now, create your observer file in the following path: after

app/code/Envision/Eecom/Observer/productSaveLater.php

<?php
namespace Envision\Eecom\Observer;

use Magento\Framework\Event\ObserverInterface;

class productSaveLater implements ObserverInterface
{
/**
* @var ObjectManagerInterface
*/
protected $_objectManager;

/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager
) {
$this->_objectManager = $objectManager;
}

/**
* customer register event handler
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
//Do your stuff here!
die('Envision Observer Is Here!');
}
}

Now, if you still have any query regarding Magento 2 observers, leave it in the comment section below.

Download Blog

ENQUIRY

Ready to Get started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    1250 Pittsford Victor Road Ste 310
    Pittsford, NY 14534

    Development Center

    Plot no. 10, Rajiv Gandhi
    Chandigarh Technology Park