How to Create Custom Event in Magento 2

Written by Jigar Patel

Oct 13, 2021

How to Create Custom Event in Magento 2

How to create custom event in Magento 2

Magento 2, Using events and observers, you can run your 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 you to create your own events that can be dispatched in your code. When an event is dispatched, it can pass data to any observers configured to watch that event.

  • Event: events are generally dispatched from the Magento\Framework\Event\Manager class. There are many core events already available to use, but you can also create custom events you want that can be dispatched in your actions’ code.
  • Observer: the observer is basically a class that implements Magento\Framework\Event\ObserverInterface interface. You can also set your own custom code or required functionality

You can define events.xml based on area. Below the type of location, you can define events.xml file.

  • Global :  [dt_highlight color=”” text_color=”” bg_color=””]etc/ folder[/dt_highlight] for admin and frontend.
  • Frontend : [dt_highlight color=”” text_color=”” bg_color=””]etc/frontend[/dt_highlight] folder for frontend scope.
  • Back End(adminhtml) : [dt_highlight color=”” text_color=”” bg_color=””]etc/adminhtml[/dt_highlight] folder for admin scope.
  • REST API : [dt_highlight color=”” text_color=”” bg_color=””]etc/webapi_rest[/dt_highlight] folder for REST API scope.
  • SOAP API : [dt_highlight color=”” text_color=”” bg_color=””]etc/webapi_soap[/dt_highlight] folder for SOAP API scope.

Introduce several ways to create custom event in Magento 2, Taken Dolphin as Package name and CustomEvent as Modulename for simplicity. code snippets are under a module named Dolphin_CustomEvent.

Before creating the custom event, we need to create a new module We already have a blog on “how to create a basic module in Magento 2“. We need to create module.xml and registration.php file. You can create module.xml and registration.php  from this tutorial.

Step:1 Create Controller (Dispatching events)

Create a “Index.php” file in the app/code/Dolphin/CustomEvent/Controller/Index folder with the following code.

<?php

namespace Dolphin\CustomEvent\Controller\Index;

use Magento\Framework\DataObject;
use Magento\Framework\App\Action\Action;

class Index extends Action
{
    public function execute()
    {
        $blogData = new DataObject(['blog_id' => '1', 'blog_title' => 'Blog Title']);
        $this->_eventManager->dispatch('dolphin_custom_event_blog',
            [
                'blog' => $blogData
            ]
        );
        echo "Dolphin Custom Event";exit;
    }
}
  • _eventManager->dispatch : is To dispatch an event, call the dispatch function of the event manager class and provide it with the name of the event you want to dispatch along with an array of data you wish to provide to observers.
  • Event Name: dolphin_custom_event_blog

Read this: Event Web API Rest and Web API Soap in Magento 2

Step:2 Create Event File

Create an “events.xml” file in the app/code/Dolphin/CustomEvent/etc folder with the following code.

<?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="dolphin_custom_event_blog">
        <observer name="dolphin_blog_custom"
                  instance="Dolphin\CustomEvent\Observer\GetBlog"/>
    </event>
</config>

This event file for admin and frontend both areas.

A name attribute is a custom event.

An instance is a class name, we have to manage events.

Step:3 Create Observer Class

Create a “GetBlog.php file in the app/code/Dolphin/CustomEvent/Observer folder with the following code.

?php

namespace Dolphin\CustomEvent\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class GetBlog implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        $blogData = $observer->getEvent()->getBlog();
        $blogId = $blogData->getBlogId();
        $blogTitle = $blogData->getBlogTitle();

        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/blog.log'); //custom log file
        $logger = new \Zend_Log();
        $logger->addWriter($writer);
        $logger->info('blog id: '.$blogId);
        $logger->info('blog title: '.$blogTitle);

        return $this;
    }
}

you can fetch data in $observer argument.

Run Command [dt_highlight color=”” text_color=”” bg_color=””]php bin/magento c:c[/dt_highlight]

Result:

Goto to the magento root/var/log you see outr custom log file blog.log

[dt_code]2021-10-05T12:04:30+00:00 INFO (6): blog id: 1
2021-10-05T12:04:30+00:00 INFO (6): blog title: Blog Title[/dt_code]

I Hope, This instruction will be helpful for you.

If you have any difficulties regarding Magento blog, do consider them posting in the Comments section below!

I’m here to help.

Thank you!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP