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


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);

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 :)

$product = $this->productRepository->getById($productId);
$product->setData($attributeCode, $attributeValue);
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
            $product = $objectManager->create('\Magento\Catalog\Model\Product');

            $prod = $product->loadByAttribute('sku', $sku);
$prod->setCustomattribute($value); // name of your custom attribute
  • got this error SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: INSERT INTO catalog_product_entity_int (entity_id,attribute_id,value,store_id) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE entity_id = VALUES(entity_id), attribute_id = VALUES(attribute_id), value = VALUES(value), store_id = VALUES(store_id) – Jay Kapoor Sep 6 '17 at 11:28
  • i used the catalog_product_save_after event/observer method for this – Jay Kapoor Sep 6 '17 at 11:28
  • please add code here – Ashar Riaz Sep 6 '17 at 11:34
  • check link magento.stackexchange.com/questions/192201/… – Jay Kapoor Sep 6 '17 at 11:40
  • i posted a new question – Jay Kapoor Sep 6 '17 at 11:40

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.