Magento 2 – Set simple product Color when creating product programmatically

The question:

Can any one help me? When I create simple product in GUI I can set color value by dropdown menu.

My question is:
How to assign color value programmatically, when I create simple product? I have spend whole day searching a way do to it.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

$attr = $_product->getResource()->getAttribute('color');
$avid = $attr->getSource()->getOptionId('Blue'); //name in Default Store View
$_product->setData('color', $avid);

I found the answer from here for a simple product. I post here the code because the post I am referring to does not point out which Product Attribute value should be used.

Method 2

I was updating product attributes programmatically and for attributes which have custom options work in this way

if ($color != '') {
 $color_attr = $prod->getResource()->getAttribute('color');
 if ($color_attr->usesSource()) {
  $colour_opt = $color_attr->getSource()->getOptionId($color);
  if ($available_color != $colour_opt) {
   $prod->setData('color', $colour_opt);
   $prod->getResource()->saveAttribute($prod, 'color');
   $notification .= 'Colour is updated for SKU ' . $sku . PHP_EOL;
   }
  }
 }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment