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']))){
  • please confirm whether you would like to implement this functionality for magento 2 api? Commented Sep 1, 2017 at 6:05

1 Answer 1


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;


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();

    $option = $this->optionFactory->create();


    // 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;
  • i am not able to create new option using this code
    – Ajay Patel
    Commented Nov 20, 2017 at 10:08

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