Magento – Magento 2: Set Custom product attribute value programmatically on product save

custom-attributesmagento2product

How to set a product's custom attribute on save?
I have used the event/observer way but nothing works.

Best Answer

Official method should work, but Not

The official method setCustomAttribute($attributeCode, $attributeValue) below should work but NOT because the official bug https://github.com/magento/magento2/issues/4703.

The bug doesn't fix yet in version 2.2.3.

$product = $this->productRepository->getById($productId);
$product->setCustomAttribute($attributeCode, $attributeValue);
$this->productRepository->save($product);

Temporary method

After many debug and tries, I found the method $product->setData($attributeCode, $attributeValue) below could set custom attribute successfully, it is a temporary method.

Hope it could help you. Any better way is welcome to post :)

private $productRepository;

public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->productRepository = $productRepository;
}

public function updateProductAttribute($productId)
{
    $attributeCode = "Attribute_code";
    $attributeValue = "Attribute Value Here";
    $product = $this->productRepository->getById($productId);
    //$product->setCustomAttribute($attributeCode, $attributeValue);
    $product->setData($attributeCode, $attributeValue);
    $this->productRepository->save($product);
}