cancel
Showing results for 
Search instead for 
Did you mean: 

Programmatically set product attribute to a certain value

Programmatically set product attribute to a certain value

Hello I am trying to create a simple product and set my custom attribute "gusto" (157) to a the value "BBBB" (5) but I can't seem to have success in any way.

The product is created just fine, but attribute is not set. This is what I have now:

 

//simple product
$simple_product = $objectManager->create('\Magento\Catalog\Model\Product');
$simple_product->setSku('test-simple' . $salt);
$simple_product->setName('test name simple' . $salt);
$simple_product->setAttributeSetId(9);

$simple_product->setData('157', '5'); // value 5 is BBBB (try here)

$simple_product->setStatus(1);
$simple_product->setTypeId('simple');
$simple_product->setPrice(10);
$simple_product->setWebsiteIds(array(1));
$simple_product->setCategoryIds(array(126)); //default
$simple_product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);

$simple_product->save();

$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
$product = $productRepository->getById($simple_product->getId());
$product->setGusto('BBBB');
$product->getResource()->saveAttribute($product, 'gusto');

$productRepository->save($product);

 

//I try multiple times to save atribute here

 

 

What am I doing wrong?

4 REPLIES 4

Re: Programmatically set product attribute to a certain value

How did you created the product attribute?

 

If you used below method then no need to write an extra code to save the custom value. Magento will take care of it. 
https://www.mageplaza.com/magento-2-module-development/magento-2-add-product-attribute-programmatica...

 

If you used the above method and set the attribute to hidden and you want to add the value to it 

You should use $simple_product->setData('gusto', '5');

 

If you still haven't success please check your reindexer if its set to scheduler then change it to after save or just run the indexer command. 
Sometimes indexer creates problem 

Re: Programmatically set product attribute to a certain value

$product = $this->productRepository->getById($productId);
$product->setCustomAttribute('gusto', 'BBBB');
$this->productRepository->save($product);

Please try this it's helpful for you.

 

Thanks.

Re: Programmatically set product attribute to a certain value

For After or Before Product Save

        <?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: Programmatically set product attribute to a certain value

 

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

$productId = 121;
$attribtueCode = 'gusto';
$value = 'BBBB';
$storeId = 1; $product = $this->productRepository->getById($productId); if you want to save new value then follow this code $product->setCustomAttribute($attributeCode, $value, $storeId); if you want to update the value then follow this code $product->addAttributeUpdate($attributeCode, $value, $storeId); $this->productRepository->save($product);