Magento – Magento 2: How to Set custom product attribute value on product save

custom-attributesmagento2product-attributesave

i have created an observer, event on before product save to set custom product attribute value, here is my code.

etc/adminhtml/events.xml

<?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_before">
        <observer name="product_save_before" instance="Learning\HelloPage\Observer\Productsavebefore" />
    </event>
</config>

Learning/HelloPage/Observer/Productsavebefore.php

<?php

namespace Learning\HelloPage\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsavebefore implements ObserverInterface
{    
    protected $authSession;

    public function execute(\Magento\Framework\Event\Observer $observer,
        \Magento\Backend\Model\Auth\Session $authSession)
    {
        $this->authSession = $authSession;
        $admin_user_id = $this->authSession->getUser()->getId();

        $_product = $observer->getProduct();  // get product object
        //set the the attribute vale
        $_product->setAttribute(admin_user_id, $admin_user_id) ?? what to do here?
    }       
}

Best Answer

Try this

<?php

namespace Learning\HelloPage\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsavebefore implements ObserverInterface
{    
    protected $authSession;

    public function execute(\Magento\Framework\Event\Observer $observer,
        \Magento\Backend\Model\Auth\Session $authSession)
    {
        $this->authSession = $authSession;
        $admin_user_id = $this->authSession->getUser()->getId();

        $_product = $observer->getProduct();  // get product object
        //set the the attribute vale
        $_product->setAdminUserId($admin_user_id);
    }       
}

But you can save the product attribute while editing the product in backend itself.