Magento2 – Get Attribute Option Label by Attribute Option ID

attributeseav-attributesmagento2

magento 2 I would like to get an attribute option label by attribute option id.

For Example:-

attribute option value : 53,

attribute option label/text/name : green

from the above scenario i want to get attribute option label/text/name.

Note: without loading product i need to get this.
please suggest me.

Best Answer

You need to add following in your __construct method

protected $optionFactory;

protected $_attributeOptionCollection;

public function __construct(
  \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory,
  \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $attributeOptionCollection
){
    $this->optionFactory = $optionFactory;
    $this->_attributeOptionCollection = $attributeOptionCollection;
}

Now you can get option data using option value;

$optionValue = 53; // your attribute value
$optionFactory = $this->optionFactory->create();
$optionFactory->load($optionValue); // load by option value
$attributeId = $optionFactory->getAttributeId(); // atribute id of given option value
$optionData = $this->_attributeOptionCollection
                ->setPositionOrder('asc')
                ->setAttributeFilter($attributeId)
                ->setIdFilter($optionValue)
                ->setStoreFilter()
                ->load(); // load option data by attribute id and given option value
echo "<pre>"; print_r($optionData->getData()); exit;
Related Topic