How to Use Event in Magento 2

0
84
views
Advertisement

In this topic, we will show you how to use event in Magento 2.

Step 1: Dispatch event
Step 2: Create events.xml file to catch the event
Step 3: Create Observer file to catch event

As Magento 2 provides an event system. It helps developers can modify or add information to a module without changing the source code of this module.

Step 1: Dispatch event

  • In Magento 2, you can dispatch the event from any place: controller, model, block, data… We will create an event from controller file.
  • File directory: app/code/Namespace/Modulename/Controller/Index/Index.php
<?php namespace Namespace/Modulename\Controller\Index; 
class Index extends \Magento\Framework\App\Action\Action 
{ 
   public function execute() {
      $hello = new \Magento\Framework\DataObject(array('label' => 'Magento 2 Event Call'));
      $this->_eventManager->dispatch('hello_magento_display', ['display' => $hello]);
      echo $hello->getDisplay();
      exit;
   }
 }
  • ‘hello_magento_display’: event name
  • [‘display’ => $hello]: event argument
  • Open your browser and use link: http://yoursite.com/modulecontroller
  • Result: Magento 2 Event Call

Step 2: Create events.xml file to catch event

File directory: app/code/Namespace/Modulename/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="hello_magento_display">
        <observer name="change_hello_magento_display" instance="Namespace/Modulename/Observer/Change" />
    </event>
 </config>

Note: Magento provides 3 events area: admin, frontend and global. In this example we can use frontend area or global area.

  • Admin area: app/code/Namespace/Modulename/etc/adminhtml/events.xml
  • Frontend area: app/code/Namespace/Modulename/etc/frontend/events.xml
  • Global area: app/code/Namespace/Modulename/etc/events.xml

Step 3: Create Observer file to catch event

File: app/code/Namespace/Modulename/Observer/Change.php

<?php namespace Namespace/Modulename\Observer; 
class Change implements \Magento\Framework\Event\ObserverInterface 
{ 
   public function execute(\Magento\Framework\Event\Observer $observer) { 
       $displayText = $observer->getData('display');
       $displayText->setDisplay('Get magento 2 event successfully!!!');
       return $this;
   }
}
  • Use the link again on your browser: http://yoursite.com/modulecontroller
  • Result was changed: Get magento 2 event successfully!!!

Get reference our another post for Get Magento 2 List of all dispatched events.