In this post I am going to explain how to get the attribute information from attribute code in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_entityAttribute;
protected $_attributeOptionCollection;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Eav\Model\Entity\Attribute $entityAttribute,
\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $attributeOptionCollection,
array $data = []
)
{
$this->_entityAttribute = $entityAttribute;
$this->_attributeOptionCollection = $attributeOptionCollection;
parent::__construct($context, $data);
}
public function getAttributeData($entityType, $attributeCode)
{
$attributeData = $this->_entityAttribute
->loadByCode($entityType, $attributeCode);
return $attributeData;
}
public function getAttributeOptions($attributeId)
{
$attributeOptions = $this->_attributeOptionCollection
->setPositionOrder('asc')
->setAttributeFilter($attributeId)
->setStoreFilter()
->load();
return $attributeOptions;
}
Add below code snippet in template file.
//attribute code
$attributeCode = 'manufacturer';
//entity type
$entityType = 'catalog_product';
$attributeData = $block->getAttributeData($entityType, $attributeCode);
echo "<pre>";
print_r($attributeData->getData());
echo "</pre>";
// get attribute id
$attributeId = $attributeData->getAttributeId();
// get attribute name
echo $attributeData->getFrontendLabel();
// get attribute default value
echo $attributeData->getDefaultValue();
//get attribute options
$attributeOptions = $block->getAttributeOptions($attributeId);
echo "<pre>";
print_r($attributeOptions->getData());
echo "</pre>";
foreach ($attributeOptions as $option) {
echo $option->getOptionId() . "<br>";
echo $option->getValue() . "<br>";
}
2. Using Object Manager
//attribute code
$attributeCode = 'manufacturer';
//entity type
$entityType = 'catalog_product';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeData = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class)
->loadByCode($entityType, $attributeCode);
echo "<pre>";
print_r($attributeData->getData());
echo "</pre>";
// get attribute id
$attributeId = $attributeData->getAttributeId();
// get attribute name
echo $attributeData->getFrontendLabel();
//get attribute default value
echo $attributeData->getDefaultValue();
//get attribute options
$attributeOptions = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)
->setPositionOrder('asc')
->setAttributeFilter($attributeId)
->setStoreFilter()
->load();
echo "<pre>";
print_r($attributeOptions->getData());
echo "</pre>";
foreach ($attributeOptions as $option) {
echo $option->getOptionId() . "<br>";
echo $option->getValue() . "<br>";
}Thats it. Enjoy Magento 2!!
Thank you.
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply