How to Create New Observer On Trigger of Magento 2 Event “catalog_product_save_before”
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”:
- Create events.xml at app\code\[Vendor]\[Module]\etc\adminhtml\events.xml
123456<?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> - Create ProductSaveBefore.php at app\code\[Vendor]\[Module]\Observer\ProductSaveBefore.php
123456789101112131415<?phpnamespace [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.
I’d like to know how you used this solution in your store in the Comments section below. Also, if you have any doubts regarding the implementation, please mention them, and I’d be glad to help.
Do share the solution on social media to help out fellow developers.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Remove Block From Layout in Magento 2
18 Tips to Prepare the Magento 2 Stores For The Holiday Season [2022]
Next