0

Using attribute Id how to get attribute label in magento 2.1. example :

    Array
       (
         [93] => 30
         [188] => 26
         [189] => 15
        ).
1

Use below code:

public function __construct(
    \Magento\Eav\Model\Config $eavConfig,
    array $data = []
) {
    $this->_eavConfig = $eavConfig;
}


$attributeObj = $this->_eavConfig->getAttribute($entityType, $code);
$attributeObj->getFrontendLabel();

For example:

$attributeObj = $this->_eavConfig->getAttribute('catalog_product', 30);
$attributeObj->getFrontendLabel();
0
$_product = $this->objectManager->get('Magento\Catalog\Model\Product')->load($product_id);

$attributes = $product->getAttributes();

foreach ($attributes as $attribute) {
     label => __($attribute->getStoreLabel()),
     'value' => $value, //attribute Value
     'code' => $attribute->getAttributeCode(), //attribute Code
}

If looking for Option Text from OptionId:

$optionId = 30;
$attribute = $_product->getResource()->getAttribute('design_color');
if ($attribute->usesSource()) {
    $optionText = $attribute->getSource()->getOptionText($optionId);
}

If looking for attribute Label from attribute Code:

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

NOTE: Inject objectManager from contructor, Direct Use of ObjectManager is not allowed as per Magento

1
  • hi @Ronak my attribute id=93 so how to get attribute label? Dec 13 '17 at 9:15
0

Try to use bellow code

<?php
namespace Namespace\Modulename\Helper;

/**
* Class Helper Data
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $eavConfig;

    public function __construct(
        \Magento\Eav\Model\Config $eavConfig
    ){
        $this->eavConfig = $eavConfig;
    }

    // pass Attribute Code and Option Value
    public function getAttributeOptionLabel($attributeCode, $optionValue){
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        $options = $attribute->getSource()->getAllOptions();
        $key = array_search($optionValue, array_column($options, 'value'));
        return strtolower($options[$key]['label']); 
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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