Today we are discussing observer in Magento 2.
To create observer in Magento 2, first we need to define observer in file:
app/code/Webkul/Hello/etc/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="controller_action_catalog_product_save_entity_after">
<observer name="Webkul_Hello_Product_Save_After" instance="Webkul\Hello\Observer\productSaveAfter" />
</event>
</config>
Note: There are different places to create files for different handlers.
- To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/frontend/events.xml
- To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/adminhtml/events.xml
- To create observer for both end, you need to create file under : app/code/Webkul/Hello/etc/events.xml
After this file, you need to create your observer file at the path you have mentioned above, i.e.:
app/code/Webkul/Hello/Observer/productSaveAfter.php
<?php
namespace Webkul\Hello\Observer;
use Magento\Framework\Event\ObserverInterface;
class productSaveAfter 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('Observer Is called!');
}
}
Thank you for reading this article on Observers in Magento 2, we hope you liked it.
You can also view our wide range of ready-to-use Magento 2 extensions.
Further for any more queries, please reach out to our team via support ticket.
5 comments
To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/frontend/event.xml
To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/adminhtml/event.xml
To create observer for both end, you need to create file under : app/code/Webkul/Hello/etc/event.xml
To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/frontend/events.xml
To create observer for frontend you can create file under : app/code/Webkul/Hello/etc/adminhtml/events.xml
To create observer for both end, you need to create file under : app/code/Webkul/Hello/etc/events.xml