Magento – How to i change product attribute value in catalog_product_save_after observer

event-observermagento-2.1magento2

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.

Best Answer

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

    }   
}