2

Helllo All,

I want to retrieve attribute code and attribute details from attribute id. In magento1, I am doing it as:

$attrCode = Mage::getModel('eav/entity_attribute')->load($attributeId)->getAttributeCode();

How can we get this in magento 2.

Thanks in advance :)

user00247
  • 638
  • 1
  • 8
  • 23

3 Answers3

8
    $eavModel = $this->_objectManager->create('Magento\Catalog\Model\ResourceModel\Eav\Attribute');
    $attr = $eavModel->load($attributeId);
    $attributeCode = $attr->getAttributeCode();//Get attribute code from its id
    echo $attributeCode;

     /*Get attribute details*/
    $attributeDetails = $this->eavConfig->getAttribute("catalog_product", $attributeCode);
    print_r($attributeDetails->getData()); 
Rohan Hapani
  • 17,388
  • 9
  • 54
  • 96
user00247
  • 638
  • 1
  • 8
  • 23
7

You can also use Magento\Catalog\Api\ProductAttributeRepositoryInterface and inject it into your class.

You can use the "get" method of the repository class. This works for me even if I supplied an attribute_id instead of the attribute_code. I've tested it in 2.2.6.

class Items extends \Magento\Framework\View\Element\Template{
    protected $repository;
    public function __construct(
        \Magento\Catalog\Api\ProductAttributeRepositoryInterface $repository
    ){
        $this->repository = $repository;
    }
    public function test($attributeId){
        $attribute = $this->repository->get($attributeId);
    }
}
Ocastro
  • 573
  • 4
  • 9
1

You can try with

 /*
  * Get attribute info by attribute code and entity type
  */ 
$attributeCode = 'color';
$entityType = 'catalog_product';

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();

$attributeInfo = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class)
                               ->loadByCode($entityType, $attributeCode);

//var_dump($attributeInfo->getData()); exit;

/**
 * Get all options name and value of the attribute
 */ 
$attributeId = $attributeInfo->getAttributeId();
$attributeOptionAll = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)
                                    ->setPositionOrder('asc')
                                    ->setAttributeFilter($attributeId)                                             
                                    ->setStoreFilter()
                                    ->load();

//var_dump($attributeOptionAll->getData()); exit;
Dhrumin
  • 861
  • 3
  • 8
  • 24