2

I am using the below code to load the attribute using attribute code but it's not working:-

protected $_attribute;

public function __construct(
   ...
   \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection $attribute,
   ...
) {
   ...
   $this->_attribute = $attribute;  
   ...  
   }

   $existingAttribute = $this->_attribute
            ->addFieldToFilter('attribute_code', $attributecode)
            ->load()
            ->getFirstItem();
        echo '<pre>'; print_r($existingAttribute); echo '</pre>';

Can any one help me in this. It's working fine as below in magento 1

$existingAttribute = Mage::getModel('eav/entity_attribute')->getResourceCollection()
            ->addFieldToFilter('attribute_code', $attributecode)
            ->load()
            ->getFirstItem();
        echo $existingAttribute->getId();   
        echo '<pre>'; print_r($existingAttribute); echo '</pre>';

Thanks for help in advance;

2
  • Up vote your answer Commented Jan 16, 2018 at 8:53
  • Your answer is okay but not that I want to implement in my code because I am working on m2 erp module that need the same code flow that I have mention in my answer. your code only load the attribute. Commented Jan 19, 2018 at 11:06

3 Answers 3

8
use \Magento\Catalog\Model\Product\Attribute\Repository;

protected $productAttributeRepository;


public function __construct(
    ...
    Repository $productAttributeRepository
    ....
) {
    ....
    $this->productAttributeRepository = $productAttributeRepository;
    ....
}

Now you can use this like to get product attribute

$yourAttribute=$this->productAttributeRepository->get('YOUR_ATTRIBUTE_CODE');
5

Try to use below code

<?php

/*add **\Magento\Eav\Model\Config** in your construct method*/

protected $eavConfig;

public function __construct(
    \Magento\Eav\Model\Config $eavConfig
){
    $this->eavConfig = $eavConfig;
}

/*Now you can get attribute data using*/


$attribute = $this->eavConfig->getAttribute('catalog_product', Your_Attribute_Code);

echo "<pre>"; print_r($attribute->getData()); exit;
-1

Please try this:

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

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

 /*Get attribute details*/
$attributeDetails = $this->eavConfig->getAttribute("catalog_product", $attributeCode);
print_r($attributeDetails->getData()); 
1
  • $options = $attributeDetails->getSource()->getAllOptions(); Include this line in second last.
    – Anees
    Commented Feb 13, 2019 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.