Event is useful feature in magento. it help develop add more functions , change data when processing some actions. Example you can use event to change price when adding product to cart. add more information when creating product . Today We will introduce how to use event in magento 2. I hope that the post will give you more useful information .

The post includes tow path Catch event and Create own event in custom Module.

  1. Catch event. Catch event allow develop can add more functions or change data when processing some action in magento. in order to catch event. you have to do two steps includes:
    • Create file events.xml in etc folder. Note. if event is global , you have to put it in You_Company/Your_modue/ect, if event only is used in frontend, you should put it in You_Company/Your_modue/ect/frontend, if event is only used in bakend, you should put it You_Company/Your_modue/ect/adminhtml/
    • Example : File  app/code/Magebay/HelloWorld/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="magento_core_event_name">
       <observer name="magebay_helloworl_event_name" instance="MagebayHelloWorldObserverEventFunction" />
       </event>
      </config>
    • Create File MagebayHelloWorldObserverEventFunction.php
      <?php
      namespace MagebayHelloWorldObserver;
      
      class EventFunction implements MagentoFrameworkEventObserverInterface
      {
        public function execute(MagentoFrameworkEventObserver $observer)
        {
           $data = $observer->getEvent()->getData('key');
              //your custom code 
           return $this;
        }
      }

      2. Create own events in your module . Magento allow create new own event in custom module . you can catch it in this module or other module . Example :

    • File app/code/Magebay/HelloWorld/Controller/Index/Index.php
      <?php
      namespace MageplazaHelloWorldControllerIndex;
      
      class Index extends MagentoFrameworkAppActionAction
      {
        public function execute()
        {
           $textDisplay = new MagentoFrameworkDataObject(array('text' => 'Hello Magebay'));
           $this->_eventManager->dispatch('magebay_helloworld_set_texts', ['text' => $textDisplay]);
          $textDisplay->setText($textDisplay);
           exit;
        }
      }
    • As you can see, if you catch the event magebay_helloworld_set_texts . Code in event will run before function $textDisplay->setText($textDisplay);. Catch own event from custom module is the same catch event from core of magento . i hope that with the information in the post. you can build the best functions which you want in magento . Thank for reading this post .

Leave A Comment?

You must be logged in to post a comment.