I am creating new products via code. I want to save a product that has a custom attribute with multiple values. So the attribute property input type is a Multiple Select (nomo_color). I know how to save a single attribute property via the method
$product->setCustomAttribute('attribute_code', id)
But how would I do this if I should save multiple values ?
I tried iterating over the values and calling the method multiple times. This doesn't work and only saves the last value.
This is my Code
$product = $this->productFactory->create();
$type = $result[2];
$article = $result[1];
$size = $result[3];
$color = $result[4];
$qualities = isset($result[7]) ? $this->formatQualityText($result[7]) : [];
$colorValues = isset($result[5]) ? $this->formatColorText($result[5]) : [];
$sku = $article.'-'.$color.'-'.$size;
$name = $article . ' - ' . $color . ' - ' . $type . ' - ' . $size;
$price = (float) isset($result[6]) ? $result[6] : 0;
$product->setSku($sku);
$product->setName($name);
$product->setPrice($price);
if ( ! empty($colorValues)) {
foreach($colorValues as $value) {
$product->setCustomAttribute('nomo_color', $this->attributeHelper->createOrGetId('nomo_color', $value));
}
}
if ( ! empty($color)) {
$product->setCustomAttribute('color', $this->attributeHelper->createOrGetId('color', $color));
}
$this->productRepository->save($product);
Best Answer
This is how I solved my problem.
You can save custom attribute id's seperated by ',' => implode(',' $ids);