0

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

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

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.