How to Use Event in Magento 2

In this article, I will show you how to use event in Magento 2. Please follow below three steps to use magento event.

  • 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 developer to modify or add information to a module without changing the core source code.

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

saveCopyzoom_out_map
<?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

saveCopyzoom_out_map
<?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

saveCopyzoom_out_map
<?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

That's it!!

Finally, we are done, let's flush or refresh cache and check Result was changed or not.

I hope this Magento article helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other handy commands which are not included in the list.

P.S. Do share this note with your team.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off