Question

I want to update product sku after save product. I had used this event :- catalog_product_save_after In Observer,

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            $productId = $observer->getProduct()->getId();
            $product = $observer->getProduct();

            $product = $observer->getProduct();       

            $sku = 'TestSku';
            $productFactory = $this->_objectManager->create('\Magento\Catalog\Model\ProductFactory');
            $otherproduct = $productFactory->create()->load($productId);
            $otherproduct->setSku($sku);
            $otherproduct->save();
       }
   }

But while saving product, it gives

No Data Found Error enter image description here

Please help me to fix it.

Was it helpful?

Solution

It's not update because you are using catalog_product_save_after event. So, on product save again event will be call. So, You can use controller_action_catalog_product_save_entity_after or catalog_product_save_before event and You can update SKU like this below code :

<?php

namespace VendorName\ModuleName\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct();  // you will get product object
        $_sku=$_product->getSku(); // check here you get sku or not.
        $_product->setData('sku','test');
        $_product->save();

    }   
}

OTHER TIPS

catalog_product_save_before use this event but dont call save function

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top