Magento, Magento 2

How to Get Product Attribute Option Id from Label in Magento 2

How to Get Product Attribute Option Id from Label in Magento 2

In this tutorial, Today I will explain to how to get product attribute option id from label in Magento 2. To get attribute option id by label, you need to use \Magento\Catalog\Model\ProductFactory class in your construct. There are dropdown, visual swatch, multi-select etc types attribute in which you can add multiple options in single attribute. For ex : Color Attribute.

You may also like this :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class GetAttrDetails extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;

    /**
     * @param  \Magento\Framework\View\Element\Template\Context $context
     * @param  \Magento\Catalog\Model\ProductFactory            $productFactory
     * @param  array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        array $data = []
    ) {
        $this->productFactory = $productFactory;
        parent::__construct($context, $data);
    }

    /**
     * Pass here attribute code and option label as param
     */
    public function getAttrOptIdByLabel($attrCode,$optLabel)
    {
        $product = $this->productFactory->create();
        $isAttrExist = $product->getResource()->getAttribute($attrCode); // Add here your attribute code
        $optId = '';
        if ($isAttrExist && $isAttrExist->usesSource()) {
            $optId = $isAttrExist->getSource()->getOptionId($optLabel);
        }
        return $optId;
    }
}

You can use this above code in block and model file. You just need to pass attribute code and attribute option label as param in getAttrOptIdByLabel($attrCode,$optLabel) function. Here, we get product attribute object from product resource and then pass option label to retrieve attribute option id.

You can call this function in template file like :


$optionId = $block->getAttrOptIdByLabel('color','Red');
echo $optionId; // You will get option ID of Red attribute option.

That’s it !!!

I hope this blog is easy to understand about how to get product attribute option id from label in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,