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 Attributes in Setup

Sometimes in our module we require to create product or category attributes automatically on module install. Also, we might require to add extra fields to quote, sales order, invoice, creditmemo tables. We will go through how to do that in magento 2. You can find the sample code in the git repo .