Magento – Magento 2: Set Product Attribute Dynamically

magento2product-attribute

How to set product attribute dynamically, I am using catalog_product_save_after event and catch the event using Observer.

here is my observer

<?php

namespace Learning\HelloPage\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    

    protected $_objectManager;

    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_objectManager = $objectManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $admin_user_id = $this->authSession->getUser()->getId();
        $_product = $observer->getEvent()->getProduct();
        $_product->setAdminUserId('2');
        // $_product->setData('admin_user_id', '2');

    }       
}

here is my 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_after">
        <observer name="product_observer" instance="Learning\HelloPage\Observer\Productsaveafter" />
    </event>
</config>

and i got this error on product save.

enter image description here

here is my custom attribute that is updated on product save.
enter image description here

Best Answer

First you need to get price and after updating then try to set it. e.g

public function updateWholeSalePrice($observer) {
    $product = $observer->getEvent()->getProduct();
    $_product->getPrice();   
    $_product->getWholesaleprice(); 
    $wholesalePrice = (float)(($_product->getPrice())*5)/100;
    $product->setWholesaleprice($wholesalePrice);
} 

see this link https://stackoverflow.com/a/24032241