0

I have a product attribute label get in category page below way.

<?php 
$tablecolor = $_product->getResource()->getAttribute('xyz'); // attribute name
$attrTestValue = $tablecolor->getFrontend()->getValue($_product);
echo $Label = $_product->getAttributeLabel('xyz');
?>

it is working fine
but it is depricated in magento 2.3
What is a suggested an alternative way to get labels without using deprecated method?

1 Answer 1

0

you can just inject an instance of Magento\Catalog\Model\ResourceModel\Product in your class and use that one instead of $product->getResource();

/**
 * @var \Magento\Catalog\Model\ResourceModel\Product
 */
private $productResource;

public function __construct(
    ...
    \Magento\Catalog\Model\ResourceModel\Product $productResource,
    ....
) {
    ....
    $this->productResource = $productResource;
    ....
}

And use this inside your methods

$tablecolor = $productResource->getAttribute('xyz'); 

This is how you can use the product resource model, but in your specific case, when you want to get an instance of a certain attribute you can use the product attribute repository

/**
 * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
 */
private $attributeRepository;

public function __construct(
    ...
    \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
    ....
) {
    ....
    $this->attributeRepository = $attributeRepository;
    ....
}

and later use this

try {
    $tablecolor = $attributeRepository->get('xyz'); 
    //do soemthing with tablecolor
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    //the attribute does not exist
}

If you want to only get the label of an option of a dropdown attribute for a specific product you can just use this

$product->getAttributeText('xyz');
3
  • Thank you for answer but i want to get attribute label how can achieve that? Commented Feb 24, 2020 at 14:09
  • I've updated the answer. It now contains a way to use the product resource model, a way to get an instance of a product attribute and how to get the attribute option label for a specific product. I hope I covered all your needs.
    – Marius
    Commented Feb 24, 2020 at 14:14
  • yes right but i want to implement in category page so how can do this ? i have no more experience with this so and custom extension create? or xyz and i am using magento 2.3.4 Commented Feb 24, 2020 at 14:19

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.