cancel
Showing results for 
Search instead for 
Did you mean: 

Unable to update custom product attribute value programatically

Re: Unable to update custom product attribute value programatically

I was tried many ways finally its worked thanks man.

Re: Unable to update custom product attribute value programatically

        <?php
    namespace vendor\module\Observer;
    
    class ProductSaveAfter implements \Magento\Framework\Event\ObserverInterface
    {
        public function __construct(
            \Magento\Backend\Model\Auth\Session $authSession,
            \Magento\Catalog\Model\ProductFactory $productFactory
        ) {
            $this->authSession = $authSession;
            $this->productFactroy = $productFactory;
        }
        public function execute(\Magento\Framework\Event\Observer $observer)
        {
            $user = $this->authSession->getUser()->getUsername();
            $productId = (int) $observer->getProduct()->getId();
            $product = $this->productFactroy->create()->load($productId);
            $product->addAttributeUpdate("updated_by", $user, 0);//attribute,value,storeid
        }
    }

Re: Unable to update custom product attribute value programatically

To Update the custom attribute value please follow the below code, it could be help you...

 

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $productRepository = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface');

$product = $productRepository->getById($productId);
$product->addAttributeUpdate($attributeCode, $attributeValue, $storeId);
$productRepository->save($product);

Thanks.