0

How to get product attribute of a product without using Object manager directly, since using Object manager is not recommended?

asked Mar 3, 2020 at 6:29

1 Answer 1

0

We can use Dependency injection for getting product attribute in magento2 which is the recommended way of getting the attribute value. It can be easily accomplished by using object manager directly, but why it is not recommended?

To use or not to use the ObjectManager directly?

The above link will answer that question.

So how can we achieve this with dependency injection. below code will give you an edge of using DI

Add this code snippet to the 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 the below code sniffer in the template or where you want to be called

//attribute code
$attributeCode = 'manufacturer';
//entity type
$entityType = 'catalog_product';
$attributeData = $block->getAttributeData($entityType, $attributeCode);
print_r($attributeData->getData());
// 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);
print_r($attributeOptions->getData());
foreach ($attributeOptions as $option) {
 echo $option->getOptionId() . "<br>";
 echo $option->getValue() . "<br>";
}
answered Mar 3, 2020 at 6:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.