5

getResource() is deprecated so my question is what do I need to use instead to be future proof for next updates.

I use this function like below in the catalog list.phtml

$seedBank = $_product->getResource()->getAttribute('brand')->getFrontend()->getValue($_product);

2 Answers 2

5

You can get product custom attribute option label directly as below:

$_product->getAttributeText('brand');

This will return label of product selected brand.

1
  • 1
    Awesome, that worked like a charm !
    – Riccardo
    Dec 2, 2019 at 11:48
4

Have an instance of \Magento\Catalog\Model\ResourceModel\Product as a dependency for your class and call methods from that class.

/**
 * @var \Magento\Catalog\Model\ResourceModel\Product
 */

private $productResource;

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

Now, in the methods where you need the value, let's say $_product is the product instance you can do this:

$seedBank = $this->productResource->getAttribute('brand')->getFrontend()->getValue($_product);
2
  • 2
    Thanks, this will work on other pages. On the Category page the following will be enough: $_product->getAttributeText('brand');
    – Riccardo
    Dec 2, 2019 at 11:51
  • $this->productResource->getAttribute('brand')->getFrontend()->getValue($_product); not productResource() is not a function
    – Yogesh
    May 19, 2021 at 5:49

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.