1

Is there a way to add new options, programmatically, for a product attribute with attribute code 'brand' that is already created from admin? I want to add new options on Controller Save action. The option values will be taken from custom admin form field(see image attached). enter image description here

Any help would be appreciated.

1 Answer 1

1

I found the solution myself:


public function __construct(
    \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
    \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory,
    \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory,
    \Magento\Framework\Message\ManagerInterface $messageManager
) {
    $this->attributeOptionManagement = $attributeOptionManagement;
    $this->optionLabelFactory = $optionLabelFactory;
    $this->optionFactory = $optionFactory;
    $this->messageManager = $messageManager;
}

public function addOptions() {
    
    $eavConfig = $this->_objectManager->create(\Magento\Eav\Model\Config::class);
    $attribute = $eavConfig->getAttribute('catalog_product', 'brand');
    $existingValues = $attribute->getSource()->getAllOptions(); // get existing attribute option values
    $existingLabels = [];
    foreach ($existingValues as $existingValue) {
        $existingLabels[] = explode(',', $existingValue['label']);
    }

    $labels = ['testvalue34']; // add new attribute value here

    if (!in_array($labels, $existingLabels)) {
        foreach ($labels as $label) {
            $optionLabel = $this->optionLabelFactory->create();
            $optionLabel->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
            $optionLabel->setLabel($label);

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

            $this->attributeOptionManagement->add(
            \Magento\Catalog\Model\Product::ENTITY,
            'manufacturer',
            $option
            );
        } 
        $messageManager->addSuccess(__("New attribute value saved"));

    } else {
        $messageManager->addError(__("Attribute value already exists"));
    }
}

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.