Skip to content
Advertisement

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 MagentoFrameworkEventObserver $observer
     * @return void
     */
    public function execute(
        MagentoFrameworkEventObserver $observer
    ) {
        $_product = $observer->getProduct(); // you will get product object
        $_sku = $_product->getSku(); // for sku
        $_product->setSku("testNew1");
        $_product->save();
    }

Advertisement

Answer

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 it’s 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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement