In Magento 2 We can get product Attributes Option Id from the Label and Option label by Option id with Product Factory object.
Occasionally when you work with the Configurable Product type you may face situations to get Option Id or Label from the Attribute code.
Lets We have taken a Color attribute to demonstrate the usage, Find a Color Label value based on Color Option id.
<?php
namespace Rbj\ProductAttribute\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Catalog\Model\ProductFactory $productFactory
) {
$this->productFactory = $productFactory;
parent::__construct($context);
}
/* Get Label by option id */
public function getOptionLabelByValue($attributeCode,$optionId)
{
$product = $this->productFactory->create();
$isAttributeExist = $product->getResource()->getAttribute($attributeCode);
$optionText = '';
if ($isAttributeExist && $isAttributeExist->usesSource()) {
$optionText = $isAttributeExist->getSource()->getOptionText($optionId);
}
return $optionText;
}
/* Get Option id by Option Label */
public function getOptionIdByLabel($attributeCode,$optionLabel)
{
$product = $this->productFactory->create();
$isAttributeExist = $product->getResource()->getAttribute($attributeCode);
$optionId = '';
if ($isAttributeExist && $isAttributeExist->usesSource()) {
$optionId = $isAttributeExist->getSource()->getOptionId($optionLabel);
}
return $optionId;
}
Call Method at the specific file,
$optionValue = $this->getOptionLabelByValue('color','50'); // result is blue
$optionId = $this->getOptionIdByLabel('color','Blue'); // result is 50
Assume that, We have Option id 50 and its value is Blue from Attribute code Color.
getOptionIdByLabel() and getOptionLabelByValue() method will be use to get Option Id By Label value and Option Label by Option Id respectively.
You need to pass only the correct Product Attribute code you want to fetch the value. The given example is working fine for all the custom product attributes in Magento.