Get an Attribute (Multi)Select's Option ID in Magento 2

As a result of the EAV data structure in Magento, the options of a select or multiselect attribute are stored and retrieved by id. This poses a challenge when getting the attribute in that calling getAttName() or getData('att_name') on an object (product, customer, etc.) will return the id instead of the text value that may be expected. This is easily addressed by Magento with the method getAttributeText('att_name') which will return the text string.

Note: In the methods mentioned above "AttName" and "att_name" would be replaced by the attribute name. For instance, a "Button Count" attribute would be retrieved with getButtonCount() or getData('button_count').

On the other side, there are times on the backend when you may need to find the attribute's value id from it's text, for instance to store or add it to a new product. This takes a bit more effort, but is still relatively easy. You will need to inject Magento\Eav\Api\AttributeRepositoryInterface into your class. A minimal example using our "Button Count" attribute would be:

class Example
{
    /**
     * Attribute repository
     * 
     * @var \Magento\Eav\Model\AttributeRepository
     */
    protected $attributeRepository;

    public function __construct(
        \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository
    ) {
        $this->attributeRepository = $attributeRepository;
    }

    public function getButtonCountOptionId()
    {
        $attribute = $this->attributeRepository->get('catalog_product', 'button_count');
        return $attribute->getSource()->getOptionId('Three Buttons');
    }
}

Our getButtonCountOptionId() method would return a string containing the ID associated with the "Three Buttons" select option, such as '234'.

Note: When we inject and instantiate the interface Magento\Eav\Api\AttributeRepositoryInterface we will get an object with the class Magento\Eav\Model\AttributeRepository. This is due to the preference set by the Magento Eav module in Magento\Eav\etc\di.xml.

Referenced Files
Magento\Eav\Api\AttributeRepositoryInterface
Magento\Eav\Model\AttributeRepository
Magento\Eav\etc\di.xml

Photo by Olia Gozha at Unsplash