'magento 2 catalog_product_save_before unable to save product but keeps loading
I'm trying to save the product in the observer of event catalog_product_save_before, but somehow the admin panel is just loading, it's not saving the product.
Can anyone please suggest the solution for this?
/**
* Execute observer
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(
\Magento\Framework\Event\Observer $observer
) {
$_product = $observer->getProduct(); // you will get product object
$_sku = $_product->getSku(); // for sku
$_product->setSku("testNew1");
$_product->save();
}
Solution 1:[1]
This approach will cause a loop. Because the catalog_product_save_before is dispatched before every product save. And in this observer you do $_product->save(); which again will dispatch this event and come in this observer where the save() method is called again, etc.
As you get the $product in the observer before its save, it should just work to adjust the product object and it will be saved afterwards.
So remove the line $_product->save(); and it should work fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
