Magento – how to set Custom Select and MultiSelect value while Product add Programatically Magento 2

magento-2.1magento2multiselect-attributeproduct-attributeselect

I am working on to create a simple product programmatically.

I have created 2 custom Attribute

  1. Select(select_testing)
  2. MultiSelect(multiselect_testing)

select_testing attribute value ==> 1, 2, ,3, 4.
multiselect_testing attribute value –> 1, 2, 3, 4.

So, I try to add Product using following code.

  $_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
  $simple_product = $_objectManager->create('\Magento\Catalog\Model\Product');
  $simple_product->setSku('test-sku');
  $simple_product->setName('SimpleProduct');
  $simple_product->setRkTesting('Rk Testing');
  $simple_product->setSelectTesting('1');
  $simple_product->setMultiselectTesting(array("1","2"));
  $simple_product->setYesTesting(1);
  $simple_product->save();

But, Select and Multiselect attribute value not save.

Suggest me, how to add Select and multiselect Attribute value.

Best Answer

You should use

Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend

as 'backend_model' for your "multiple" attribute

and update attribute by follow:

$_product->addAttributeUpdate('attribute_code', 'value', $storeId);
Related Topic