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.

asked Jan 18, 2022 at 11:07

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"));
 }
}
answered Jan 18, 2022 at 12:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.