Menu Close
    Hire us Request quote Reading list Switch to dark mode

    How to create custom observers in magento2

    In this blog We are going to explain you how to create your own custom event (observer) in magento2. 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 observer

    public function execute()
                    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 */
            }catch (\Magento\Framework\Exception\LocalizedException $e) {
                return $this->resultRedirectFactory->create()->setPath('*/*/');
            }  catch (Exception $e) {
                return $this->resultRedirectFactory->create()->setPath('*/*/');

    Step 2- Calling the custom observer

    <?xml version="1.0"?>
    <config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
        <event name="custom_observer_name">
            <observer name="custom_observer_method" instance="Webkul\Grid\Observer\CustomObserverMethod"/>

    Step 3- creating custom observer method

    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)
                $eventData = $observer->getData();
                // Write your code here
            }catch(Exception $e){

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

    . . .


    Add Your Comment

    Be the first to comment.

    Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just received your message and our expert will get back to you shortly.
    Send Again