Skip to main content

Magento - Get Attribute Option Text from Option Id


If you have the attribute code and the option value id for the data, then we can get the text value for the option by the below code. The below code is for product, you can use the same logic to get the data for other eav resource models like customer, category, etc.



public function getOptionValue($field, $value) {
    $attribute = $this->getAttribute($field);
    if (!is_null($value) && $attribute) {
        if ($attribute->usesSource()) {
            $text_value = array();
            foreach(explode(",", $value) as $sub_value) {
                $text_value[] = $attribute->getSource()->getOptionText($sub_value);
            }
            return implode("|", $text_value);
        }
    }

    return $value;
}

The function take attribute code and value as input. If the attribute uses source to get the values, then get the text for the option id, else it return the value as it, as it is not an option.

You can get the attribute data from the link http://mage-simplified.blogspot.in/2016/02/magento-get-attributes-from-attribute.html

Comments

Popular posts from this blog

Magento 2 - Create Attributes in Setup

Sometimes in our module we require to create product or category attributes automatically on module install. Also, we might require to add extra fields to quote, sales order, invoice, creditmemo tables. We will go through how to do that in magento 2. You can find the sample code in the git repo .