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;
}