0

How can I change the attribute of a product in catalog_product_save_after event.

I am getting the product object. I set data in a particular attribute and set $product->save().

This stops everything, admin page doesn't open at all. I have to fire service php-fpm restart.

2
  • You should add your code in the question so that someone can analyse the issue more effectively. – Dinesh Yadav Jun 22 '18 at 11:27
  • The below ans is same like my code. – Avesh Naik Jun 22 '18 at 12:29
-1

If you want to $productobj after saving product from backend then you can easily use catalog_product_save_after event.

Put this events.xml in below path

app\code\YOUR_NAMESPACE\YOURMODULE\etc\adminhtml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="test_name" instance="YOUR_NAMESPACE\YOUR_MODULENAME\Observer\Productsaveafter" />
    </event>
</config>

And put your Productsaveafter.php in below path

app\code\YOUR_NAMESPACE\YOURMODULE\Observer\

<?php

namespace YOURNAMESPACE\YOURMODULENAME\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{  
    protected $_productloader;  


    public function __construct(
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {
        $this->_productloader = $_productloader;
    }

    public function getLoadProduct($id)
    {
        return $this->_productloader->create()->load($id);
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $value = 'Your value';
        $_product = $observer->getProduct();  // you will get product object
        $_productloader = $this->getLoadProduct($_product->getId()); // for sku
        $_productloader->setCustomattribute($value); // name of your custom attribute
        $_productloader->save();

    }   
}
3
  • Ok i will try this one – Avesh Naik Jun 22 '18 at 11:44
  • No not working "Gateway Timeout" – Avesh Naik Jun 22 '18 at 12:10
  • You are forgetting something. You are calling save method, so you are calling this observer again and again. – Avesh Naik Jun 22 '18 at 15:15

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.