0

I have a collection of product I am looping and displaying for E.G

...    
$product->getName()
...
$product->getProductUrl()
...

Now Also I am getting it some option like attributeText foreach product E.G

$product->getAttributeText('color') // this gives me red,green,blue so on...

Now My question is how do I get ID:

$product->getAttributeId('color')

I know that in \Magento\Catalog\Model\Product there is a function like so:

/**
 * Get attribute text by its code
 *
 * @param string $attributeCode Code of the attribute
 * @return string
 */
public function getAttributeText($attributeCode)
{
    return $this->getResource()->getAttribute($attributeCode)->getSource()->getOptionText(
        $this->getData($attributeCode)
    );
}

I could and I did test and it worked so potentially I could do a function :

 public function getAttributeId($attributeCode)
{
    return $this->getResource()->getAttribute($attributeCode)->getSource()->getOptionId(
        $this->getData($attributeCode)
    );
}

That works but how to implement this outside of vendor folder or if there is another way to get the id even better please share.

Thanks.

1
  • Please check my answer. Commented Oct 13, 2018 at 7:53

2 Answers 2

0

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 you can use that in your class

$attribute = $this->eavConfig->getAttribute('catalog_product', 'attribute_code_here');
$options = $attribute->getSource()->getAllOptions();
$values = [];
foreach ($options as $OptionData) { 
        $values[] = $OptionData->getId();
}
    return $values;

Don't use Object Manager Directly.

0

You can use this to get custom and default attribute option data. For example:

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$atrributesRepository  = $objectManager->create('\Magento\Catalog\Model\Product\Attribute\Repository');
$selectOptions = $atrributesRepository->get('AttributeCode')->getOptions();
foreach ($selectOptions as $selectOption) {
    print_r($selectOption->getData());
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.