Skip to main content
3 of 3
added 215 characters in body
HelgeB
  • 4.6k
  • 2
  • 12
  • 27

The following code assumes that a product attribute with the attribute_code $code exists. For adding a new attribute please check some appropriate questions, e.g. Magento 2 - Create product attribute programmatically

For adding new attribute values it is better to use the values key in the option array. This is expects entries with key sortOrder and value label, while the approach you are using expects the optionId as key.

Change your code like this:

$attribute = $this->_eavConfig->getAttribute('catalog_product', $code); $attributeId = $attribute->getAttributeId(); $option = array(); $i=1; //sortOrder counter $option['attribute_id'] = $attributeId; //use the 'values' key to add new option values; that array contains the sort_order as key and the label as value $option['values'][$i++] = 'value1'; $option['values'][$i++] = 'value2'; //... $this->_eavSetup->addAttributeOption($option); 

For better understanding of what'S happening there you can check the method addAttributeOption($option) in Magento\Eav\Setup\EavSetup.

I hope that helps. Feedback would be nice.

HelgeB
  • 4.6k
  • 2
  • 12
  • 27