Magento 2 events and observers enable to extend the default functionality. The developers can use them to run custom code in response to a particular Magento 2 event.
I have used one of the Magento 2 events, “catalog_product_save_before” and shown the method below for the same.
Some of the examples where you can follow this solution are when you want to get notified as an admin on product quantity update, custom attribute update, etc.
Earlier, I had used this event in the method to auto change “Stock Availability” on quantity update in Magento 2
Steps to Create New Observer On Trigger of Magento 2 Event “catalog_product_save_before”:
1. Create app\code\[Vendor]\[Module]\etc\adminhtml\events.xml
<?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="catalog_product_save_before"> <observer name="observer_name" instance="Meetanshi\CustomModule\Observer\ProductSaveBefore" /> </event> </config>
2. Create ProductSaveBefore.php at app\code\[Vendor]\[Module]\Observer\ProductSaveBefore.php
<?php namespace [Vendor]\[Module]\Observer; use Magento\Framework\Event\ObserverInterface; class ProductSaveBefore implements ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $product = $observer->getProduct(); $sku = $product->getSku(); $id = $product->getId(); $name = $product->getName(); } }
That’s it.
Do share the solution on social media to help out fellow developers.
Thanks.