0

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.

2

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();

    }   
}
  • I tried all the possible ways including this, actually save function is not working here, Is there any other way to update product sku after save product? – Himani Aug 5 at 9:15
  • Please check my updated answer and change your events. – Rohan Hapani Aug 5 at 9:20
  • 1
    It worked , Thanks – Himani Aug 5 at 9:31
  • Happy to Help :) Happy coding !! – Rohan Hapani Aug 5 at 9:32
1

catalog_product_save_before use this event but dont call save function

  • To update sku, I need product id aswell. because in new sku I am going to give product id. But in before event I will not get product id. – Himani Aug 5 at 9:23
  • you will get the id check it once – mohith Aug 5 at 9:25
  • It worked with this event: controller_action_catalog_product_save_entity_after, thanks for help. – Himani Aug 5 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.