If you want to create product attribute options programatically, but not by admin then this blog post is right the solution for you.
You need to add below code in controller.
Codes for 2.2.x & 2.3.x will be different.
Code for Magento 2.2.X :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$optionLabel = $this->optionLabelFactory->create(); $optionLabel->setStoreId(0); $optionLabel->setLabel($attoption); $option = $this->optionFactory->create(); $option->setLabel($optionLabel); $option->setStoreLabels([$optionLabel]); $option->setSortOrder(0); $option->setIsDefault(false); $this->attributeOptionManagement->add(\Magento\Catalog\Model\Product::ENTITY, $this->attributeRepository->get($attrname)->getAttributeId(),$option); $_product = $this->productFactory->create(); $isAttributeExist = $_product->getResource()->getAttribute($attrname); $optionId = ''; if ($isAttributeExist && $isAttributeExist->usesSource()) { $optionId = $isAttributeExist->getSource()->getOptionId($attoption); } return $optionId; |
Code for Magento 2.3.X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$optionLabel = $this->optionLabelFactory->create(); $optionLabel->setStoreId(0); $optionLabel->setLabel($attoption); $option = $this->optionFactory->create(); $option->setLabel($attoption); $option->setStoreLabels([$optionLabel]); $option->setSortOrder(0); $option->setIsDefault(false); $this->attributeOptionManagement->add(\Magento\Catalog\Model\Product::ENTITY, $this->attributeRepository->get($attrname)->getAttributeId(),$option); $_product = $this->productFactory->create(); $isAttributeExist = $_product->getResource()->getAttribute($attrname); $optionId = ''; if ($isAttributeExist && $isAttributeExist->usesSource()) { $optionId = $isAttributeExist->getSource()->getOptionId($attoption); } return $optionId; |
I hope adding the above codes in their respective versions of your Magento store will help you to create product attribute options. Let us know by comment if it worked for you or not?
[crayon-63e0a4c7a8310542932008/] Using above fucntion Images can be imported directly from...
Override view block using di.xml and add the below code...
You can check a list of called layout XML for...
Follow the below steps to install and set up PWA...
If you want to remove all leading zero's from order,...
Let our Magento expert connect to discuss your requirement.
We offer Magento
certified developers.
Our Magento clientele
is 500+.
We sign NDA for the
security of your projects.
We’ve performed 100+
Magento migration projects.
Free quotation
on your project.
Three months warranty on
code developed by us.