In today’s blog, we are showing how to add option values to product attributes programmatically in Magento 2.
....
protected $_attributeRepository;
protected $_attributeOptionManagement;
protected $_option;
protected $_attributeOptionLabel;
....
public function __construct(
.......
\Magento\Eav\Model\AttributeRepository $attributeRepository,
\Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
\Magento\Eav\Api\Data\AttributeOptionLabelInterface $attributeOptionLabel,
\Magento\Eav\Model\Entity\Attribute\Option $option,
..........
) {
.....
$this->_attributeRepository = $attributeRepository;
$this->_attributeOptionManagement = $attributeOptionManagement;
$this->_option = $option;
$this->_attributeOptionLabel = $attributeOptionLabel;
.....
}
public function addAttributeOptionValue() {
$attribute_id = $this->_attributeRepository->get('catalog_product', 'product_brand')->getAttributeId();
$name = "Your First Value";
/* new attribute option */
$this->_option->setValue($name);
$this->_attributeOptionLabel->setStoreId(0);
$this->_attributeOptionLabel->setLabel($name);
$this->_option->setLabel($this->_attributeOptionLabel->getLabel());
$this->_option->setSortOrder(0);
$this->_option->setIsDefault(false);
$optionAdded = $this->_attributeOptionManagement->add('catalog_product', $attribute_id, $this->_option);
}
Hope this helps!
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply