0

Magento 2.4: I have a custom product attribute called shop_status. It has two possible options:

  • ACTIVE
  • INACTIVE

I would like to get the option ID from the text label, eg:

$id = $attribute->getOptionValue('ACTIVE');

Is there any function to do this?

I know I can get a list of the options and loop through to find like so:

$attribute = $this->attributeRepository->get(
    'catalog_product',
    'shop_status'
);
$options = $attribute->getOptions();
foreach ($options as $option) {
    // If label == ACTIVE
}

Is there a better way to do this?

1 Answer 1

0

Try Below Code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productData = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface')->getById(12);// addd Product ID
echo $productData->getResource()->getAttribute('shop_status')->getFrontend()->getValue($productData);

OR

protected $productRepository;

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

public function getLabelName($prdId)
{
    $productData = $this->productRepository->getById($prdId);// addd Product ID
    return $productData->getResource()->getAttribute('shop_status')->getFrontend()->getValue($productData);
}
2
  • Thanks but this requires a product with the attribute. I don't have that. I only have the attribute and the option label from which I want to get the option ID.
    – CrazyHorse
    Jan 11 at 14:14
  • you need to pass only attribute code here. It's the return option label of a responsive product.
    – Msquare
    Jan 12 at 4:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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