Site icon MageComp Blog

How to Perform Operation When Any New Product is Created in Magento 2

How to Perform Operation When Any New Product is Created in Magento 2

Hello Magento Friends,

Today I am going to explain How to Perform Operation When Any New Product is Created in Magento 2.

New products keep on arriving while working with the eCommerce store. Magento offers 6 types of products that can be used to manage the catalog. Learn more about Magento 2 Product Types and Create your Custom Product Type in Magento 2.

When a user creates a new product, sometimes there is a requirement to perform any operation like assigning a category to the newly created product in Magento 2. To do this, you can follow the below-given steps.

Steps to Perform Operation When Any New Product is Created in Magento 2:

Step 1: First, we need to create an “events.xml” file inside our extension at the following path.

app\code\Vendor\Extension\adminhtml\etc\

Now, add the below code

<?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_after">
        <observer name="product_save_after" instance="Vendor\Extension\Observer\Productsaveafter" />
    </event>
</config>

Step 2: After that, we need to create a “Productsaveafter .php” file inside the extension Model directory.

app\code\Vendor\Extension\Observer\

And then add the following code

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct();
        if($_product->isObjectNew())
        {
                   // code for modification
        }            
    }   
}

Conclusion:

This is all for now! Accordingly, you can easily perform any action on the latest product created in Magento 2. If you have any queries, feel free to comment below. Share the solution with others and stay in the loop with us.

Happy Coding!

Exit mobile version