Magento 2 – get option label from drop down
A often search task is how to get option label from drop down. For beginners this may be confusing, because the actual value of a drop down product attribute is a number and not a text as expected. I show you how this works and what you need to know about drop down product attributes.
Magento 2 – get option label from drop down
You get option label from drop down the same way as Magento 1, with a getOptionText function. But step by step. First we need a product (get product by id):
1 | $_product = $this->_objectManager->get('Magento\Catalog\Model\Product')->load($product_id); |
Now you get the label with following line of code:
1 | $_product->getResource()->getAttribute('design_color')->getFrontend()->getValue($_product); |
Where design_color is the name of my drop down attribute. With this simple code you get the label of the attribute which was set in product backend. In some special situation you may also want to get option id of a label or a label based on a known option id.
Get label based on option id
The value of a drop down product attribute is an option id. This is something you don’t want to display anywhere. With this internal database id you can get the corresponding value based on your local store. This works with the following code:
1 2 3 4 5 | $optionId = 27; $attribute = $_product->getResource()->getAttribute('design_color'); if ($attribute->usesSource()) { $optionText = $attribute->getSource()->getOptionText($optionId); } |
Get option id based on label
The other way round is also possible. Sometimes you know a label and want to get the option id.
1 2 3 4 5 | $optionLabel = "blue"; $attribute = $_product->getResource()->getAttribute('design_color'); if ($attribute->usesSource()) { $option_id = $attribute->getSource()->getOptionId($optionLabel); } |
Create new drop down product attribute
If you do not know how to create new drop down product attributes, here is a short tutorial. Go to Stores –> Product. With button “Add New Attribute” you can define your own new product attribute. Lets create an additional color attribute:
Click save and your attribute will be created in database. The only thing you need to do now is to add it to your attribute set.
Conclusion
Working with option labels and option ids is not much different in Magento 2.
Hi,
Great article!
Is it possible in backend (edit product) to show both admin value and store view value in attribute dropdowns?
Or just default store attribute value. The admin attribute value is used as data for exchange with external system.
Like this question:
http://magento.stackexchange.com/questions/165243/attribute-values-names-in-admin-side-as-store-view-values-magento2
I’m also wondering about the same question as Petter Granberg.
Hi!
I’m new to Magento and it is not clear where should I add this code to get text value from the dropdown.
Could you please help me?
Hey, you can use this code in your *.phtml frontend files.
Thank you!