2

How to add attribute options value if not exist in magento2 programmatically...

I am using dropdown attribute and I want to add dynamic options if not exist in dropdown .. and set product data...

Here is my code but not working: VendorName = 'ACER'

if(isset($pdata['VendorName']) && !(empty($pdata['VendorName']))){
   $_product->setVendorName($pdata['VendorName']);
}
1
  • please confirm whether you would like to implement this functionality for magento 2 api? Sep 1, 2017 at 6:05

1 Answer 1

3

To add dropdown attribute option value. You need to specify the below dependencies in your class contructor:

public function __construct(
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
        \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory,
        \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
) {
    $this->eavConfig                    = $eavConfig;
    $this->attributeOptionManagement    = $attributeOptionManagement;
    $this->optionLabelFactory           = $optionLabelFactory;
    $this->optionFactory                = $optionFactory;

    parent::__construct($context);
}

Add below function in current class and call with attribute code and new value like: addAttributeOption('color', 'red')

public function addAttributeOption($attributeCode, $value)
{
    /** @var \Magento\Eav\Model\Entity\Attribute\OptionLabel $optionLabel */
    $optionLabel = $this->optionLabelFactory->create();
    $optionLabel->setStoreId(0);
    $optionLabel->setLabel($value);

    $option = $this->optionFactory->create();
    $option->setLabel($optionLabel);
    $option->setStoreLabels([$optionLabel]);
    $option->setSortOrder(0);
    $option->setIsDefault(false);

    $this->attributeOptionManagement->add(
        'catalog_product',
        $attributeCode,
        $option
    );

    // Get the inserted ID. Should be returned from the installer, but it isn't.
    $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
    $optionId = $attribute->getSource()->getOptionId($value);

    return $optionId;
}
1
  • i am not able to create new option using this code
    – Ajay Patel
    Nov 20, 2017 at 10:08

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