Event and Observers in Magento2
To create observer in magento2, first we need to define observer in file:
app/code/Rahul/HelloWorld/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="Rahul_HelloWorld_Product_Save_After" instance="Rahul\HelloWorld\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/Rahul/HelloWorld/etc/frontend/event.xml
To create observer for frontend you can create file under : app/code/Rahul/HelloWorld/etc/adminhtml/event.xml
To create observer for both end, you need to create file under : app/code/Rahul/HelloWorld/etc/event.xml
After this file, you need to create your observer file at the path you have mentioned above, i.e.:
app/code/Rahul/HelloWorld/Observer/ProductSaveAfter.php
<?php
namespace Rahul\HelloWorld\Observer;
use Magento\Framework\Event\ObserverInterface;
class ProductSaveAfter implements ObserverInterface
{
protected $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager
) {
$this->_objectManager = $objectManager;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$storeId = $observer->getEvent()->getData('store_id');
//Do your stuff here!
die('Observer Is called!');
}
}
app/code/Rahul/HelloWorld/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="Rahul_HelloWorld_Product_Save_After" instance="Rahul\HelloWorld\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/Rahul/HelloWorld/etc/frontend/event.xml
To create observer for frontend you can create file under : app/code/Rahul/HelloWorld/etc/adminhtml/event.xml
To create observer for both end, you need to create file under : app/code/Rahul/HelloWorld/etc/event.xml
After this file, you need to create your observer file at the path you have mentioned above, i.e.:
app/code/Rahul/HelloWorld/Observer/ProductSaveAfter.php
<?php
namespace Rahul\HelloWorld\Observer;
use Magento\Framework\Event\ObserverInterface;
class ProductSaveAfter implements ObserverInterface
{
protected $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager
) {
$this->_objectManager = $objectManager;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$storeId = $observer->getEvent()->getData('store_id');
//Do your stuff here!
die('Observer Is called!');
}
}
Comments
Post a Comment