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. 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);

  2. Then, load all its options:

    if (is_object($productAttribute) && $productAttribute->usesSource()) {
                    $allOptions = $productAttribute->getSource()->getAllOptions();


  3. 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,''];
        $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

  • Thank you for your answer !but it's not clear for me Jul 13 '20 at 16:49
  • 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 '20 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 '20 at 17:30
  • I'm there too ! Jul 13 '20 at 17:43
  • Hi, I used your module can you show me how to call it in a phtml file please Jul 14 '20 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.