0
    public function getOptions($attributeCode)
    {
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        $tmpOptions = $attribute->getSource()->getAllOptions();
        $options = [];
        foreach ($tmpOptions as $option) {
            if ($option['value'] > 0) {
                $options[] = $option;
            }
        }
        return $options;
    }

I've the above code to get the options of an attribute, it works but it is only retrieving the labels of the options without the option codes that I stored in the database. From the below picture, I need the values EARTH, MUSHROOM, PLOW, instead of Cross Weave Earth, Cross Weave Mushroom, and Cross Weave Plow. But the above code is only retrieving the labels, is it possible to get the codes through a native method of the EAV handler? or which is the best way to get these values in a block class and pass it to the phtml file?

enter image description here

1 Answer 1

0

For Getting Select values make sure you load the product store wise

/** Magento\Catalog\Model\ProductFactory **/
$product = $this->productFactory->create()->setStoreId($this->storeId)->loadByAttribute('entity_id', $id);

just use getData('attribute_code'); on Product Object

$product->getData('attribute_code');

The above code will return the code values.

Else If you Want the Select Labels, then use the code below

public function getExtractedData($product, $value = '') {
        $attrValue = $product->getData($value);
        $attr = $product->getResource()->getAttribute($value);
        if ($attr && ($attr->usesSource() || $attr->getData('frontend_input') == 'select')) {
            $labelValue = $attr->getSource()->getOptionText($attrValue);
            if (is_object($labelValue)) {
                $labelValue = $labelValue->getText();
            }
            $attrValue = $labelValue;
        }
        return $attrValue;
    }

In the Above Function pass the Product Object as $product and attribute_code as $value

2
  • Thank you Mohd, unfortunately I'm not able to rate your answer as valid, but it helped me a lot Commented Mar 17, 2023 at 15:15
  • Much appreciated, thanks Commented Mar 19, 2023 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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