Saturday, October 14, 2017

Magento 2 - How to get custom attribute value without calling Product->load() first

If you'd like to access a custom attribute, but don't want to call the resource-intensive Product::load() method beforehand, you can grab the value with the method below:
Magento\Catalog\Model\ResourceModel\AbstractResource::getAttributeRawValue($product_id, $attribute_code, $store_id)

$value = $product->getResource()->getAttributeRawValue($product->getId(), 'attribute_code', $product->getStoreId());
This returns the raw value, so for a multi-select you'll get a numeric value, like 52. To turn that into the text value, use:
$text = $product->getResource()->getAttribute('attribute_code')->getSource()->getOptionText($value);
Example with Magento 2.2.0 Sample Data:
// For this example, I am using Product ID 1 ("Joust Duffle Bag") and set the bag color to orange in the admin.

$value = $product->getResource()->getAttributeRawValue($product->getId(), 'color', $product->getStoreId());
$text = $product->getResource()->getAttribute('color')->getSource()->getOptionText($value);

echo "Color     : ".$value."\n"; // outputs '56'
echo "Color     : ".$text."\n";  // outputs 'Orange'

// Alternatively, once you have the value, you can set it and call getAttributeText() for the text value

echo "Color     : ".$product->getAttributeText('color')."\n"; // outputs 'Orange'

No comments:

Post a Comment