2

I have a custom attribute with code 'manufacturer'.

Its Catalog Input Type for Store Owner is 'Dropdown'.

How can i set the value for this attribute programmatically on product save. I am trying this, but unsuccessful

  $product->setManufacturer('ICM');
  $product->save();

What is the correct syntax for saving this type of attribute value

1 Answer 1

1

You have to use the id of the option as parameter for setManufacturer.
If you don't know the ids you can retrieve first all the options for the manufacturer attribute and create an array where the key is the label and the value is the id.
Something like this (all needs to happen in a class)

/**
 * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
 */
private $attributeRepository;
/**
 * @var array
 */
private $options;

public function __construct(
    ....
    \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
    ....
) {
    ... 
    $this->attributeRepository = $attributeRepository;
    ....
}

private function getOptions()
{
    if ($this->options === null) {
        try {
            $attribute = $this->attributeRepository->get('manufacturer');
            $this->options = [];
            foreach ($attribute->getOptions() as $option) {
                $this->options[$option->getLabel()] = $option->getValue();
            }
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
             $this->options = [];
         }
    }
    return $this->options;
}

after this, in the same class, in the method that saves the products you can do this:

$optionLabel = 'ICM';
$product->setManufacturer($this->getOptions()[$optionLabel] ?? null);
$product->save();

(untested code so watch out for typos).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.