1

I have used below code for add new attribute options in magento 2.

 if (!$optionId) {

            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $attribute_id = $this->getAttribute($attributeCode)->getAttributeId();

            $languageValues[0] = $label;
            $languageValues[1] = $label;

            $attr = $objectManager->create('\Magento\Eav\Model\Entity\Attribute'); 
            $attr->load($attribute_id); 

            $option = []; 
            $option['value'][$languageValues[0]] = $languageValues; 
            $attr->addData(array('option' => $option));

            $attr->save();

            // Get the inserted ID. Should be returned from the installer, but it isn't.
            $optionId = $this->getOptionId($attributeCode, $label, true);
        }

But its work only when attribute option is alphabet when i am trying with numeric value its not work.

1 Answer 1

1

I have find out solution for above problem.

public function createOrGetId($attributeCode, $label)
    {

        $optionId = $this->getOptionId($attributeCode, $label);

        if (!$optionId) {

            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $attribute_id = $this->getAttribute($attributeCode)->getAttributeId();

            $languageValues[0] = $label;
            $languageValues[1] = $label;
            $languageValues[2] = $label;
            $languageValues[3] = $label;

            $attr = $objectManager->create('\Magento\Eav\Model\Entity\Attribute'); 
            $attr->load($attribute_id); 

            $option = array(); 
            $option['value'][$attributeCode] = $languageValues; 
            $attr->addData(array('option' => $option));

            $attr->save();

            // Get the inserted ID. Should be returned from the installer, but it isn't.
            $optionId = $this->getOptionId($attributeCode, $label, true);
        }

        return $optionId;
    }

Your Answer

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

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