Reading list Switch to dark mode

    How to create custom observers in magento2

    Updated 4 March 2024

    How to create custom observers in magento2. :

    In this example we will should you How to create a event in Magento 2.

    This can be done by using event dispatcher and event observers .

    In this blog We are going to explain you about what are event dispatchers and event observers.

    Now we want to dispatch an event which allow other module can change the word displayed. We will change the controller like this:

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    For this firstly we declare a event whenever we want like I am going to declare this observer in controller execute method-

    Step 1- Declaration of event in Controller

    public function execute()
        {
            try{
                if($this->getRequest()->isPost()){
                    if (!$this->_formKeyValidator->validate($this->getRequest())) {
                        return $this->resultRedirectFactory->create()->setPath('*/*/');
                    }
                    ..
    
                    /* Here want to create to execute some code whenever this controller will be executed - So we create custom event here */
    
                    $this->_eventManager->dispatch(
                        'custom_observer_name',
                        [$this->getRequest()->getParams()]
                    );
    
                    ..
                }            
            }catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
                return $this->resultRedirectFactory->create()->setPath('*/*/');
            }  catch (Exception $e) {
                $this->messageManager->addError($e->getMessage());
                return $this->resultRedirectFactory->create()->setPath('*/*/');
            }
        }

    Here, we have dispatched an event named “custom_observer_name”.

    NOTE

    The dispatch method will receive 2 arguments: an unique event name and an array data.

    For this we need to create a file events.xml at app / code / {vendor name} / {module name} / etc / and declare out custom observer as shown in the code below :

    Step 2- Declare the custom observer

    <?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="custom_observer_name">
            <observer name="custom_observer_method" instance="Webkul\Grid\Observer\CustomObserverMethod"/>
        </event>
    </config>

    In this file, under config element, we define an event element with the name is the event name which was dispatch above.

    The class which will execute this event will be define in the observer element by instance attribute.

    Step 3- creating custom observer method : 

    Now, we will create a custom observer file named “CustomObserverMethod.php” at app / code / {vendorname} / {modulename} / Observer /

    namespace Webkul\Grid\Observer;
    
    use Magento\Framework\Event\ObserverInterface;
    
    class CustomObserverMethod implements ObserverInterface
    {
        /**
         * custom event handler
         *
         * @param \Magento\Framework\Event\Observer $observer
         * @return void
         */
        public function execute(\Magento\Framework\Event\Observer $observer)
        {
            try{
                $eventData = $observer->getData();
                // Write your code here
            }catch(Exception $e){
                $this->messageManager->addError($e->getMessage());
            }
        }
    }

    NOTE:

    The excute method of this file will get called when the dispatcher event is called which we have prepared above in the first file.

    Now use the data to perform any custom operation which is required and after that the code after the dispatch event will get executed .

    So in this way you can create and call your own custom event easily.

    You can also check the below links  :

    https://developer.adobe.com/commerce/php/development/components/events-and-observers/

    https://webkul.com/blog/magento2-use-plugins/

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home