Magento 2 Create custom event and observer using events.xml programmatically.

Magento 2 Supports Create Custom Event Observer with your event name.

Under your module with the event defines using dispatch() method and events.xml file. You can Handle the Events data using Observer Class.

Definition of dispatch() method to create custom Event:

public function dispatch($eventName, array $data = []);

$eventName: You have to call the dispatch method with $eventName is your custom event name.
$data: Contains array to get value inside Observer class.

Once you declare the events you need to define events using events.xml file.

You can define events.xml based on your required area,
Five Type of Location you can define your events.xml file,

1. Global:
etc/ folder is the configuration that can be used in both admin and frontend.

2. Frontend area:
etc/frontend folder will be used for the frontend area.

3. Back End(admin panel) area:
etc/adminhtml folder will be used for the admin area.

4. REST API Events:
etc/webapi_rest folder will be used to the REST API area.

5. SOAP API Events:
etc/webapi_soap folder will be used to the SOAP API area.

Create a Simple Module to define Custom Event with Magento 2 Way,

  • Step 1:

Dispatch Event using Controller:
We are creating a custom event for our module using the Controller file, We need to first define event using below way, (Jesadiya_CustomEvent is module name)

File: app/code/Jesadiya/CustomEvent/Controller/Index/Index.php

Custom Event Name: jesadiya_custom_event_observer

If you are trying to create a custom event using Plugin (Plugin with controller execute method), You need to define $_eventManager using class Magento\Framework\Event\ManagerInterface;

  • Step 2:

Create an event file with a specific area,
File: app/code/Jesadiya/CustomEvent/etc/events.xml

name attribute is our custom event.
instance name is a class name, where we have to handle events.

  • Step 3:

Now Create Observer file to handle our event with execute() methods,
File: app/code/Jesadiya/CustomEvent/Observer/GetRecord.php

You can fetch Event Data using a $observer argument.

We have passed a ‘record’ array using our custom event and we will capture that record data under the observer class.

Run bin/magento cache:clear

Your Custom event are triggered once you call the above Controller.