i have product attribute in dropdown i want to get all option of that attribute how i get programtically
2 Answers
you can add to the constructor of your class an instance of \Magento\Eav\Model\Config like this:
protected $eavConfig;
public function __construct(
...
\Magento\Eav\Model\Config $eavConfig,
...
){
...
$this->eavConfig = $eavConfig;
...
}
then
$attribute = $this->eavConfig->getAttribute('catalog_product', 'attribute_code_here');
$options = $attribute->getSource()->getAllOptions();
$arr = [];
foreach ($options as $option) {
if ($option['value'] > 0) {
$arr[] = $option;
}
}
Out put
(
[0] => Array
(
[value] => 280
[label] => option1
)
[1] => Array
(
[value] => 281
[label] => option2
)
[2] => Array
(
[value] => 282
[label] => option3
)
[3] => Array
(
[value] => 283
[label] => option4
)
)
Which is better? Answer is below.
\Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository ultimately at end call $attribute = $this->eavConfig->getAttribute($entityTypeCode, $attributeCode); You can judge by it which is better. :-)
1st call file : vendor\magento\module-catalog\Model\Product\Attribute\Repository.php method
public function get($attributeCode)
{
return $this->eavAttributeRepository->get(
\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE,
$attributeCode
);
}
2nd file call : vendor\magento\module-eav\Model\AttributeRepository.php
public function get($entityTypeCode, $attributeCode)
{
/** @var \Magento\Eav\Api\Data\AttributeInterface $attribute */
$attribute = $this->eavConfig->getAttribute($entityTypeCode, $attributeCode);
if (!$attribute || !$attribute->getAttributeId()) {
throw new NoSuchEntityException(
__(
'The attribute with a "%1" attributeCode doesn\'t exist. Verify the attribute and try again.',
$attributeCode
)
);
}
return $attribute;
}
Using Product Repository :-
protected $productAttributeRepository;
public function __construct(
\Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
){
$this->productAttributeRepository = $productAttributeRepository;
}
After This You Can Get Options Like This :-
$options = $productAttributeRepository->get('attribute_code')->getOptions();