How to Create Events and Observers in Magento 2?

Overview

In this blog we are going to learn the following:

  • How to dispatch an event in Magento 2?
  • How to create events.xml file?
  • How to create Observer Class?

Events and Observers in Magento 2

Working with events and observers is one of the main ways to extend Magento functionality. Using events and observers, we can run our custom code in response to a specific Magento event or even a custom event. Events are dispatched by modules when certain actions are triggered. In addition to its own events, Magento allows us to create our own events that can be dispatched in our code. When an event is dispatched, it can pass data to any observers configured to watch that event.

Step 1 : Create all the commonly needed files:

Refer this blog and create module.xml file inside etc folder and registration.php file inside Code5fixer/Eventsexample folder. Here, Eventsexample is the name of the module folder.

i.e.,

app/code/Code5fixer/Eventsexample/etc/module.xml app/code/Code5fixer/Eventsexample/registration.php

Step 2: Create Controller file:

In this controller file, we specify the dispatch method of an event.

Create a folder inside Eventsexample folder and name it as Controller. Inside Controller folder, create a folder and name it as Index and inside Index folder, create a php file and name it as Test.php

app/code/Code5fixer/Eventsexample/Controller/Index/Test.php

The contents of Test.php file will be:

Test.php:

<?php
namespace Code5Fixer\Eventsexample\Controller\Index;
class Test extends \Magento\Framework\App\Action\Action
{
  public function execute()
  {
    $textDisplay = new \Magento\Framework\DataObject(array('text' => 'Code5Fixer'));
    $this->_eventManager->dispatch('code5fixer_eventsexample_display_text', ['mp_text' => $textDisplay]);
    echo $textDisplay->getText();
    exit;
  }
}
                

Step 3 :Create an event file: events.xml:

Custom events can be dispatched by simply passing in a unique event name to the event manager when we call the dispatch function. Our unique event name is referenced in our module’s events.xml file where we specify which observers will react to that event.

To create an events.xml file, create a folder inside etc folder and name it as frontend ( as we are going to display the text in frontend ) and inside frontend folder, create an xml file and name it as events.xml

app/code/Code5fixer/Eventsexample/etc/frontend/events.xml

The contents of events.xml file will be:

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="checkout_cart_product_add_after">
        <observer name="customprice" instance="Code5fixer\Eventsexample\Observer\CustomPrice" />
    </event>
</config>                
                    

The class which will execute this event, will be defined in the observer element by instance attribute.

Step 4: Create routes.xml file:

To make a Controller to work, we need routes.xml file inside frontend folder of the etc folder.

app/code/Code5fixer/Eventsexample/etc/frontend/routes.xml

The contents of routes.xml file will be :

routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">                    
    <router id="standard">
        <route frontName="helloworld" id="helloworld">
            <module name="Code5fixer_Eventsexample" />
        </route>
    </router>
</config>                  
                        

Step 5: Create Observer class:

Observer is a certain type of Magento class that can influence general behavior, performance, or change business logic. Observers are executed whenever the event that are configured to watch is dispatched by the event manager. To create an observer, we must place our class file under our /Observer directory. Our observer class should implement Magento\Framework\Event\ObserverInterface and define its execute function

To implement this, create a folder inside our module and name it as Observer. Inside Observer folder create a php file and name it as ChangeDisplayText.php

app/code/Code5fixer/Eventsexample/Observer/ChangeDisplayText.php

The contents of ChangeDisplayText.php file will be

ChangeDisplayText.php

<?php
namespace Code5Fixer\Eventsexample\Observer;
class ChangeDisplayText implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
    $displayText = $observer->getData('mp_text');
    echo $displayText->getText() . " - Event </br>";
    $displayText->setText('Events and Observers example module is executed successfully.');
    return $this;
}
}               
                        

This class will implement the ObserverInterface and declare the execute method.

Step 6 : Run all the necessary commands

We need to run commands like setup:upgrade, static-content:deploy, setup:di:compile, reindex and cache:flush from the Magento root directory.

To know more about more magento commands, refer this blog.

Let us open the below URL in our browser

http://yourhost.com/helloworld/index/test

And now, our browser will be as shown below.

We hope, with the help of the above steps, you will be easily getting the customer collection in Magento2. Also, share this blog with your developer friends.

You could also download the above module here

After downloading this module:

  1. Extract the downloaded zip file
  2. Paste the extracted Code5fixer folder into /app/code/ folder in your magento root directory.
  3. Run all the necessary 5 commands and check for output.
This module is developed using Magento ver. 2.4.3-p1 version. But if you try this in older or newer versions, it may give some errors.

You could also refer to this demo video for better understanding.

We hope our guide would be very useful for you. If you have any questions, feel free to reach us anytime by leaving a comment below.

Check out our new blogs here

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments