Magento, Magento 2

How to Get Attribute Code using Attribute Id in Magento 2

How to Get Attribute Code using Attribute Id in Magento 2

Today, I will explain to how to get attribute code using attribute id in Magento 2. When you develop any custom logic at that time, maybe you need to get attribute code to fetch any attribute information. At that time, you need to pass attribute id to get attribute code.

For that, we should follow some code logic steps to get attribute code. Let’s follow the steps to get attribute code :

You may also like this :

Method 1 (Construct Method):

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

class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * \Magento\Eav\Model\Entity\Attribute
     */
    protected $attribute;

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

    public function getCustomAttributeCode()
    {
        $attribute = $this->attribute->load(93); // pass attribute id here
        return $attribute->getAttributeCode();
    }
}
?>

I added this code in block. You can use anywhere this code by inject \Magento\Eav\Model\Entity\Attribute class in your construct. After that, you can call getCustomAttributeCode() function to get attribute code.

Method 2 (Object Manager):

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attribute = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class)->load(93); // pass attribute id here
echo $attribute->getAttributeCode();

I do not recommended to use object manager method. Always use dependency injection method.

That’s it !!!

I hope this blog is easy to understand about how to get attribute code using attribute id 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 ,