Magento, Magento 2

Create custom events in Magento 2

Create custom events in Magento 2

In this technical blog, I will explain you how to create custom events in Magento 2. Custom events helps to add details without change the core code in Magento 2. First of all, let’s see about observer. There are different ways to extend core functionality. Moreover, Magento 2 events and observer is one of the best way among them.

What is observer?

An Observer is a class that implements the Magento\Framework\Event\ObserverInterface interface. In observers, you can set your custom required functionality or code logic which is to be executed in response.

What is events?

Events are dispatch with the help of Magento\Framework\Event\ManagerInterface. Also, There are so many core events available and you can also create your own custom events which can be dispatched in your actions code. It will pass data to the relevant observer which configured for the event on action trigger. It dispatched from Magento\Framework\Event\Manager class.

Now, let’s start to create custom event in Magento 2.

In addition, If you want to create simple module, you can check here.

Step 1 : Firstly, create a Magento 2 event, add a new file events.xml in app/code/RH/Helloworld/etc/frontend and add this below code

<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="rh_customobserver_log">
        <observer name="rh_log_text" instance="RH\Helloworld\Observer\CustomObserver" />
    </event>
</config>

<observer> tag properties :

  • name : name attribute indicate that it’s an observer name. It must be unique per event definition.
  • instance : Instance attribute value is a Magento class.
  • disabled : For set value of observer active or not.
  • shared : Shared attribute determine the created instance is shared or not. Default value is false.

Step 2 : Secondly, Create controller file for declaration of observer CustomObserverFile.php in app/code/RH/Helloworld/Controller/Index and add this below code

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

class CustomObserverFile extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context      $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $this->_eventManager->dispatch('rh_customobserver_log', ['custom_text' => 'Custom Observer']);
        $resultPage->getConfig()->getTitle()->prepend(__('Welcome to RH Custom Observer module'));
        return $resultPage;
    }
}
?>

Step 3 : Thirdly, Create observer file CustomObserver.php for custom observer method at app/code/RH/Helloworld/Observer and add this below code

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Observer;

class CustomObserver implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $observer_data = $observer->getData('custom_text');
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/Rohan.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info($observer_data);
        return $this;
    }
}

Finally, flush cache and execute {base_url}/helloworld/index/customobserverfile controller. After that, you can see in your var/log/Rohan.log file that custom_text value display in log file.

I hope this blog is easy to understand about how to create custom event in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged ,