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.

U Can used this and Get Custome And Defult attributes Option Data, For Example

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

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.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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