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

here is my observer


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->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" />

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


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

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

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

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.