I'm looking for having attribute option value from its label
Indeed I have a list of labels ans I want to generate their value s of each one.
1 Answer
First load your product attribute from its attribute code
/** \Magento\Eav\Model\Config $eavConfig */
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $eavAttribute */ $productAttribute = $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeCode);
Then, load all its options:
if (is_object($productAttribute) && $productAttribute->usesSource()) { $allOptions = $productAttribute->getSource()->getAllOptions();
}
Finally, find the option value from the label:
/** Magento\Eav\Model\Entity\Attribute\Source\Table $eavSourceTable */
$attributeTable = $eavSourceTable->setAttribute($attribute); $allOptions = $eavSourceTable->getAllOptions(false);
foreach ($allOptions as $option) { if ($option['label'] == $label) { return $option['value']; } } $count = count($allOptions) +1; $data['option']['value']['option_' . $count] = [$label,'']; $attribute->addData($data); $attribute->getResource()->save($attribute); $attributeTable = $eavSourceTable->setAttribute($attribute); $options = $eavSourceTable->getAllOptions(false); foreach ($options as $option) { if ($option['label'] == $label) { return $option['value']; } }
all this code, will need to be part of a class. I imagine you see from there where to put this code and where to declare the dependencies for it
-
-
Thanks for your feedback Nouari, if you could point me to an answer that you have accepted, I may see how I can change my answer to suit you Jul 13, 2020 at 17:11
-
Ok, it's done then, I have already a code if you can verify this for me please, can we continue on a discussion? Jul 13, 2020 at 17:30
-
-
Hi, I used your module can you show me how to call it in a phtml file please Jul 14, 2020 at 11:32