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 2 - Create a simple module

In magento 2, the creation of module has changed completely. We will go through how to create a module. Like earlier magento, we do not need to put our module files in different folders for code, theme, skin, etc. All, the codes related to the module should be inside one main folder. You can find the sample code in the git repo .