How to show the drop down attribute value using getData() method in magento 2?
Pergunta
When I try to get data from the material attribute like $_product->getData('material')
, it shows the integer value. How can I convert it to the actual front-end value and in which file do I have to make the changes?.
Solução
Instead of getData()
you need to use getAttributeText('attribute_code')
for dropdown attributes. like
$_product->getAttributeText('material');
For multi-select try this :
$result = $_product->getResource()->getAttribute('material')->getFrontend()->getValue($_product);
Outras dicas
To fetch value of attribute Use:
$this->getProduct()->getAttributeText('material');
Or
$this->getProduct()->getResource()->getAttributeRawValue($this->getProduct()->getId(),'material',$this->_storeManager->getStore()->getId());
You can get product attribute option values by below code
$_product->getAttributeText('material');
You can get multi select option values by
$_attributeValue = $block->getProduct()->getResource()->getAttribute('sizing_guidelines')->getFrontend()->getValue($block->getProduct());
$_product->getAttributeText('material');
is the right answer --- beware that $_product->getResource() is a deprecated function
The answers above were partially missing something (at least for my case, since I needed to use the custom attribute value inside the cart template), if you want to pass the custom attribute to a template proceed like this:
Create File catalog_attributes.xml inside /etc folder of any existing module
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
<group name="quote_item">
<attribute name="insert_here_your_attribute_code"/>
</group>
</config>
and from inside the template, in case of attribute of type select
<?php /* @escapeNotVerified */ echo $product->getAttributeText('attribute_code') ?>
where
$product = $block->getItem()->getProduct()
$block in this case was \Magento\Checkout\Block\Cart\Item\Renderer
In case of attribute of type text instead
<?php /* @escapeNotVerified */ echo $product->getCustomAttribute('attribute_code')->getValue() ?>
after that just execute
bin/magento c:c
And you should see the value of the custom attribute in your cart page or any other template files.