Skip to main content

Magento 2 - Events and Observer


In magento 2, events have been changed from events tag in config.xml to events.xml file in etc folder or etc/adminhtml/ folder or etc/frontend/ folder. You can find the sample code in the git repo.

Create a module as per the blog post. Inside etc folder, the events.xml file typically will have
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_category_load_after">
        <observer name="vendorname_samplemodule" instance="VendorName\SampleModule\Observer\CategoryLoadAfter" />
    </event>
</config>

The observer class CategoryLoadAfter.php should have the below code.
<?php

namespace VendorName\SampleModule\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

class CategoryLoadAfter implements ObserverInterface {

    public function execute(Observer $observer) {
        $category = $observer->getEvent()->getCategory();
        //code to use the observer event
        return $this;
    }

}


Comments

Popular posts from this blog

Magento - Unit Testing

Magento 2 comes with default unit testing in built. But, for magento 1, it is very difficult to perform unit testing. There is an extension EcomDev_PHPUnit, which can help us in performing unit tests in magento 1.