Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Product Attribute Options by attribute code in Magento 2.0

I am trying to retrieve the list of dropdown attributes and check if the value exists (if it does i need to get the value and assign it to the product) and if it doesnt i will have to create it and get its value to assign it to the product.

$attribute = $this->objectManager->create('Magento\Eav\Model\Entity\Attribute');
$attributeId = $attribute->getIdByCode('catalog_product','manufacturer');
$model = $this->objectManager->create('Magento\Catalog\Model\ResourceModel\Eav\Attribute');
$model->load($attributeId);
print_r($model->getFrontendLabel());
like image 639
Zubair Avatar asked Dec 23 '15 13:12

Zubair


3 Answers

Following Magento 2 guidelines, you should not use ObjectManager by yourself. Instead, you must use dependency injection. More info here

In your Block/Controller/Helper..., create a constructor and inject \Magento\Catalog\Api\ProductAttributeRepositoryInterface class. For example :

private \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository;

public function __construct(
    \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository
) {
    $this->productAttributeRepository = $productAttributeRepository;
}

Then, in your dedicated method, you want to call (PHPDoc added for clarity) :

/** @var \Magento\Eav\Api\Data\AttributeOptionInterface[] $manufacturerOptions */
$manufacturerOptions = $this->productAttributeRepository->get('manufacturer')->getOptions();

You can now get options values and labels this way :

foreach ($manufacturerOptions as $manufacturerOption) {
    $manufacturerOption->getValue();  // Value
    $manufacturerOption->getLabel();  // Label
}
like image 181
Yonn Trimoreau Avatar answered Nov 18 '22 19:11

Yonn Trimoreau


<?php echo $_product->getResource()->getAttribute('movement')->getFrontend()->getValue($_product);?>

$_product is the object of Product The above code returns attribute value of attribute name "movement".

like image 29
Sreenath Avatar answered Nov 18 '22 18:11

Sreenath


Using API Service layer, for EAV Attribute of any entity type, Inject the service data member in your constructor as follow.

protected $eavAttributeRepository;
public function __construct(
    ...
    \Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepositoryInterface,
    ...
){
    ...
    $this->eavAttributeRepository = $eavAttributeRepositoryInterface;
    ...
}

And the you can get the attribute using this.

$attribute = $this->eavAttributeRepository->get('catalog_product', 'attribute_code_here');
// vardump($attribute->getData());

In order to get attribute option values array, use this.

$options = $attribute->getSource()->getAllOptions();
like image 1
saiid Avatar answered Nov 18 '22 19:11

saiid