1

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;

  • Up vote your answer – Purushotam Sharma Jan 16 '18 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. – Purushotam Sharma Jan 19 '18 at 11:06
5
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');
| improve this answer | |
3

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;
| improve this answer | |
0

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()); 
| improve this answer | |
  • $options = $attributeDetails->getSource()->getAllOptions(); Include this line in second last. – Anees Feb 13 '19 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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