Pergunta

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.

Foi útil?

Solução

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

    }   
}

Outras dicas

catalog_product_save_before use this event but dont call save function

Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top