30

How to get an option value based on the option id in Magento, or get an option id based on the option code ?

Example: how to get the color attribute option id 10 from the label "Red", and get the value "Red" if the option id is 10 ?

10 Answers 10

65

you can do it same as magento 1,

More information in details, Visit, Get Option id and Label from configurable product

//get option label based on option id from product object

$optionId = 10;

$attr = $_product->getResource()->getAttribute('color');
 if ($attr->usesSource()) {
       $optionText = $attr->getSource()->getOptionText($optionId);
 }
//get option text ex. Red

//get option id based on option label

$attr = $_product->getResource()->getAttribute('color');
 if ($attr->usesSource()) {
       $option_id = $attr->getSource()->getOptionId("Red");
 }

//get option id ex. 10
7
  • Can you tell me what is the use of $attr->usesSource() while getting attribute options
    – Jaisa
    Commented Mar 21, 2018 at 12:49
  • I got the options without the if condition what you have mentioned in your code
    – Jaisa
    Commented Mar 21, 2018 at 12:49
  • Can you explain , If i am wrong
    – Jaisa
    Commented Mar 21, 2018 at 12:50
  • 1
    perfect rakesh bhai mlishu kyarek avad ma :) ! made my day!!! +1 :) Commented Nov 29, 2018 at 7:11
  • Thanks, I used this piece of code but I am facing issues now. See magento.stackexchange.com/questions/256510/…. Is there maybee an alternative method to achieve the same result?
    – Akif
    Commented Jan 2, 2019 at 21:37
21

I get a simple solution. This will only show the attribute value with the attribute code for a product. I have checked the catalog and details page.

This code is simple and will work for select and similar type attributes.

<?php echo $_product->getAttributeText('size'); ?>

This code will work for multiselect type attributes.

<?php echo $_product->getResource()->getAttribute('size')->getFrontend()->getValue($_product);?>

here size is the attribute name.

0
14

Best practice in magento is to do it via xml.

To get a standard attribute like brand you do something like this in catalog_product_view.xml for example:

<referenceBlock name="product.info.main">
    <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.brand" template="product/view/attribute.phtml" before="-">
        <arguments>
            <argument name="at_call" xsi:type="string">getBrand</argument>
            <argument name="at_code" xsi:type="string">brand</argument>
            <argument name="css_class" xsi:type="string">brand</argument>
            <argument name="at_label" xsi:type="string">none</argument>
            <argument name="add_attribute" xsi:type="string">itemprop="brand"</argument>
        </arguments>
    </block>
</referenceBlock>

This will get the value of an input attribute or textarea. If you have a dropdown you should use the text type, so add this line in the list of arguments:

<argument name="at_type" xsi:type="string">text</argument>

No need to create files or write any php code to get an attribute. This way you will have consistency and use the same attribute.phtml file for all attributes. If something changes you need to change it in one place only.

2
  • You just saved my day, I was not able to get 'dropdown ' text, and I found this. so thanks. Commented Aug 8, 2016 at 11:26
  • Hi, @Cladiu Creanga I am trying to show the dropdown text in the checkout page using knockout js. But only the ID of the dropdown value is getting displyed.
    – skm
    Commented Feb 14, 2020 at 6:01
14

Worked for me

$_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);
0
7

Use Factory Method

   protected $_attributeLoading;

   public function __construct( 
        .....
          \Magento\Catalog\Model\ResourceModel\ProductFactory   $attributeLoading,  
          ....
                                ) {
            parent::__construct($context);

            ....
            $this->_attributeLoading = $attributeLoading;
            ....

    }


   public function getAttributeOptionId($attribute,$label)
    {
        $poductReource=$this->_attributeLoading->create();
        $attr = $poductReource->getAttribute($attribute);
         if ($attr->usesSource()) {
                return  $option_id = $attr->getSource()->getOptionId($label);
         }
    }
   public function getAttributeOptionText($attribute,$label)
    {
        $poductReource=$this->_attributeLoading->create();
        $attr = $poductReource->getAttribute($attribute);
         if ($attr->usesSource()) {
                return  $option_Text = $attr->getSource()->getOptionText($label);
         }
    }

in phtml file

  $this->getAttributeOptionId('color','//optionLabel');
  $this->getAttributeOptionText('color','//optionId');
2
  • hi @Qaisar, can we create attribute programmatically without installer Commented Jan 8, 2019 at 6:09
  • @jafarpinjar yes you can do that. using same code. Commented Jan 8, 2019 at 7:44
5

$product->getResource() has a DocBlock note about being deprecated at least in v2.2.2 and so I was hesitant to code using it. Came up with this solution instead inspired by the ones already on this page:

$optionId = $product->getDataByKey('attribute_code');
$optionText = null;
$attributes = $product->getAttributes();
if ($optionId && array_key_exists('attribute_code', $attributes)) {
    $attr = $attributes['attribute_code'];
    if ($attr->usesSource()) {
        $optionText = $attr->getSource()->getOptionText($optionId);
    }
}
if ($optionText) {
    //do something with $optionText
}

For reference this is the method in AbstractModel.php

/**
 * Retrieve model resource
 *
 * @return \Magento\Framework\Model\ResourceModel\Db\AbstractDb
 * @deprecated 101.0.0 because resource models should be used directly
 */
public function getResource()
{
    return $this->_getResource();
}
2
  • Where do you see this code in original Magento? I can't even find getResource() method in this model: github.com/magento/magento2/blob/2.3-develop/app/code/Magento/…
    – zitix
    Commented Jan 12, 2019 at 11:42
  • getResource() was a method which previously existed. In v2.2.2 as I mentioned it was already slated for deprecation. In the 2.3-develop branch I suspect it has been completed. Thus my example which does not require that function. Commented Jan 15, 2019 at 23:59
5

For everyone comes here.

If you don't have any product entity, you could retrieve an option value with this steps.

Inject \Magento\Eav\Api\AttributeRepositoryInterface to your class

public function __construct(
    ...
    \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository,
    ...
) {
    ...
    $this->attributeRepository = $attributeRepository;
    ...
}

Use the repo to get the attribute instance

// 4 is the default entity_type_id for product
$attribute = $this->attributeRepository->get('4', '[attribute_code]');

Use $attribute to get the option id from the option value

$optionId = $attribute->getSource()->getOptionId('[option_value]');
2

you can use for getting attribute label

$product->getResource()->getAttribute($key)->getFrontend()->getLabel($product);

you can using object manager :

$pid = 1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$pdata = $objectManager->create('Magento\Catalog\Model\Product')->load($pid);

$getlable = $pdata->getResource()->getAttribute($key)->getFrontend()->getLabel($pdata);
0

Please try this code

Step 1)First you have to load the products

$_productCollection = $block->getLoadedProductCollection();

Step 2)In the product listing page ,there will be a foreach loop for listing the products like this

foreach ($_productCollection as $_product)

Step3)Your code will be inside this loop.Place the below code at a place whereever you want to display the attribute label.

$_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);

Just replace your_attribute_code with whatever your attribute is named.

0

You can use this method: \Magento\Catalog\Model\Product::getAttributeText()

Your Answer

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