How to get the attribute id by attribute code in magento 2
-
11-01-2021 - |
Question
I have the attribute code, But how do I check whether the attribute is exist in the attribute set or not. Please provide me a solution how to get the attribute id from attribute code in magento 2
Solution
Get Attribute Id By Attribute Code In Magento2.
Just you have to follow some steps.
Create constructor
/**
* @var \Magento\Eav\Model\ResourceModel\Entity\Attribute
*/
protected $_eavAttribute;
/**
* @param Context $context
* @param \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
*/
public function __construct(
Context $context,
\Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute
)
{
$this->_eavAttribute = $eavAttribute;
parent::__construct($context);
}
//Call the getIdByCode method of Attribute in any method.
//Your $this->_eavAttribute->getIdByCode('entity_type', 'attribute_code');
$attributeId = $this->_eavAttribute->getIdByCode('customer', 'company_name');
Also you can check more details here.
OTHER TIPS
You can also use a product attribute repository class to do this:
public function __construct(
\Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository,
) {
$this->productAttributeRepository = $productAttributeRepository;
}
public function example()
{
$attribute = $this->productAttributeRepository->get('size');
$sizeId = $attribute->getAttributeId();
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$entityAttribute = $objectManager->get('Magento\Eav\Model\ResourceModel\Entity\Attribute');
$attributeId = $entityAttribute->getIdByCode('ENTITY TYPE', 'ATTRIBUTE CODE');
for example, get the
product attribute
ID with the attribute codebrand
:
$attributeId = $entityAttribute->getIdByCode('catalog_product', 'brand');
Try this one-
https://webkul.com/blog/get-attribute-id-attribute-code-magento2/
You can also see how we can get customer and company name.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange