PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

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

 May 17, 2022     magento-2.0, php     No comments   

Issue

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());

Solution

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
}


Answered By - Yonn Trimoreau
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing