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?
If you want get query string params in controller file,...
Create di.xml and add the below code Magemonkey/Redirect/etc/frontend/di.xml [crayon-62838a01935be174118338/] Create...
You can try below code to change local date to...
Step 1: First you need to add registration.php file in...
Step1 : Override message.js in current theme file on the...