Skip to main content

Events and Observers in Magento2

Events and Observers in Magento2




We can customize the core functionality of magento2 in different ways and this is one of them.

In this tutorial, we’ll get to know about how we can use events and observers in Magento2.


Events and Observers are used to run your custom code in response to a specific magento event or custom event. We can use the magento events or we can create our custom events to execute our code when that particular event associated with the observer gets dispatched.


Events in Magento2


First, we’ll create events.xml to declare our event and the observer class which will be called on an event dispatch.

events.xml can be created according to area specific. 

Vendor/Module/etc/adminhtml/events.xml is used for the admin area. 

Vendor/Module/etc/frontend/events.xml is used for the frontend area. 

Vendor/Module/etc/events.xml is used for both the frontend and admin area. 


Here we are creating our events.xml under etc/frontend/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="Custom_event_action">

       <observer name="display_custom_text"instance="Custom\Module\Observer\CustomText" />

   </event>

</config>


Here, 

Event name will be the name of the event, we’ll mention our custom event name or magento event name. 

Observer name is a name of the observer and it cannot be the same for different observers. 

Instance will be the observer class which will be called on an event dispatch. 


Dispatch Event


Events can be dispatched using the  Magento\Framework\Event\Manager class. We have to inject this class in our controller’s constructor and call the dispatch function of this class and add the event name you want to dispatch also we can pass the array of data to observer using dispatch function. 


Create Custom\Module\Controller\Index.php to dispatch an event. 


<?php

 

namespace Custom\Module\Controller\Index;

 

class Index extends \Magento\Framework\App\Action\Action

{

 

   public function execute()

   {

       $customtext = new \Magento\Framework\DataObject(array('text' => 'Event Declared'));

       $this->_eventManager->dispatch(Custom_event_action, ['cs_text' => $customtext]);

       echo $customtext>getText();

       exit;

   }

}


Observers in Magento2


Observer is a class to add your required functionality on an event dispatch. Observers are created into the Observer\ folder of your module. 


The Observer class should implement the Magento\Framework\Event\ObserverInterface class. We can also get data passed by dispatch function in our observer. 


<?php

 

namespace Custom\Module\Observer;

 

class CustomText implements \Magento\Framework\Event\ObserverInterface

{

   public function execute(\Magento\Framework\Event\Observer $observer)

   {

       $displayText = $observer->getData('cs_text');

       echo $displayText->getText() . " - Event </br>";

       $displayText->setText('Execute event successfully.');

 

       return $this;

   }

}


Observers are configured to observe that whenever the event gets triggered the functionality of the observer will be applied. 


We can also disable observer using disable attribute in 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="Custom_event_action">

       <observer name="display_custom_text" disabled="true" />

   </event>

</config>


Comments

Popular posts from this blog

Magento2 CLI

Magento2 CLI  Back after a long break! Starting again with this blog because I found it the most important to understand if we are doing the magento development as magento commands play the most important role here. It really helps us a lot if we know that lĺwhich command we need to run on this action or after any changes.  Let’s start with the basic commands that we use a lot of times during our development.  cache:clean or cache:flush php bin/magento cache:clean Or  php bin/magento  cache:flush Both of these commands are used to clean the cache of Magento2 so that your new changes can be reflected to your store.  Using cache:clean it deletes all the enabled cache of magento2. Disabled caches are not affected with cache:clean but if you are doing cache:flush then it purges all the cache storage of magento wherever its enabled or disabled or it even deletes all the third party cache along with the magento cache.  If you are doing any changes in admin configuration, layout xml file, u

How EAV Model Works in Magento2?

                         How EAV Model Works in Magento2?  EAV Model stands for Entity-Attribute-Value is a very important concept of magento2 to understand how the attributes of entities are stored and works in magento2.  EAV Model is described as :-  Entity - Entity refers to the data items such as customers,orders,catalog,category etc.  Attribute - Attributes of the entities like price is an attribute of the product(entity) is referred here is an attribute. Value - A value of the attribute as $20 is a value for price attribute is referred here is a value.  Use of EAV Model EAV(Entity-Attribute-Value) is used to create new attributes of entities such as products, categories etc. With the use of eav models we don’t need to change the structure of the core tables of attributes thus it increases the scalability of the system.  Let’s have a look at how eav works in Magento2 -  Eav model used many several tables to store the data of the entity attributes. The top most table for the e

Plugins in Magento2

Plugins in Magento2 Unlike Magento1, Magento2 introduces a whole new concept of Plugins or Interceptor. A plugin or interceptor is used to change the behaviour of the method of any class without affecting the actual class. This is a very powerful way to customize the core classes of Magento2.  Plugins are one of the customization methods in Magento2. In plugins, there is a design pattern called “Interception” which means “Inserting code dynamically without changing original class behaviour” and this is what plugins exactly do in Magento2. Plugins modify the behaviour of a plugin class function by intercepting a function call and adding code before, after and around that function’s call.  Plugins are used with public methods only.  Declaring Plugins To declare plugins in Magento2, we have to create di.xml according to the specific area.  Create di.xml inside Vendor/Module/etc for global.   < config >     < type name = "{ObservedType}" >       < plugin name