Magento 2 custom events

In Magento 2, you can create custom events by defining them in your module’s events.xml file and dispatching them from your code where needed. Here’s how you can do it:

  1. Define the Event in events.xml:

Create a file named events.xml in the etc directory of your module. Define your custom event inside this file.


<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="custom_event_name">
        <observer name="custom_event_observer" instance="Vendor\Module\Observer\CustomEventObserver" />
    event>
config>

Replace custom_event_name with the name of your custom event and Vendor\Module\Observer\CustomEventObserver with the class that will observe this event.

  1. Create the Observer Class:

Create a PHP class for your observer. This class will contain the logic that should be executed when the custom event is dispatched.


namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class CustomEventObserver implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // Your custom logic here
    }
}

Replace Vendor\Module\Observer\CustomEventObserver with the appropriate namespace and class name.

  1. Dispatch the Event:

You can dispatch the custom event from any part of your code where it’s needed using the EventManager.


namespace Vendor\Module\Model;

use Magento\Framework\Event\ManagerInterface;

class YourClass
{
    protected $eventManager;

    public function __construct(
        ManagerInterface $eventManager
    ) {
        $this->eventManager = $eventManager;
    }

    public function dispatchCustomEvent()
    {
        $eventName = 'custom_event_name'; // Name of your custom event
        $eventData = ['custom_data' => 'value']; // Optional data to pass to the observer

        $this->eventManager->dispatch($eventName, $eventData);
    }
}

Replace 'custom_event_name' with the name of your custom event.

Now, whenever you call dispatchCustomEvent() method, your custom event will be dispatched, and the logic defined in your observer class will be executed.



Copyright © 2013-present Magesystem.net All rights reserved.