Magento – Using $_product->getMsrp() in price.phtml Template

priceproductproduct-attributetemplate

I am struggling to understand why the msrp attribute is unavailable in
~/template/catalog/product/price.phtml

I can access it fine from within product/view.phtml

I have defined a custom attribute for a product and have no problem accessing it with (for example):

$_product->getAttributeText('custom_attribute');

However:

$_product->getAttributeText('msrp'); 

and

 $_product->getMsrp(); 

both return null.

I would really appreciate figuring out how to

a) access this value but more importantly

b) know why some attributes seem to be available via standard getters, while others aren't

EDIT: So attribute is actually available in price.phtml when viewing single product pages, however in this case i'm calling a category list view.

Best Answer

Product collections by default load a subset of the products' attributes, unlike $product->load() which loads all product attributes. You have to make sure that the msrp attribute is loaded by the product collection you're using. See Mage/Catalog/etc/config.xml, the config/frontend/product/collection/attributes node:

In your module's config.xml you can add msrp:

<config>
...
    <frontend>   
        <product>
            <collection>
                <attributes>
                    <msrp />
                </attributes>
            </collection>
        </product>
    </frontend>
...
<config>

Alternatively, you can tap into the block that loads the product collection and do a $productCollection->addAttributeToSelect('msrp');. Another option is to also add an observer to the product collection load before event and again add the attribute to the select.

/Edit: If System -> Configuration -> Catalog -> Frontend -> Use Flat Catalog Product is enabled, product collections on the frontend read from the flat tables. That means that the attribute has to be one of the attributes indexed this way otherwise it will be silently ignored (addAttributeToSelect does nothing). An attribute to be indexed in the flat tables has to meet a few conditions that I don't remember exactly right now. I think the attribute has to be Used in product listing, Use in Layered Navigation and something else.

Cheers

/Edit: adding information from the comments

getAttributeText() should be used only for Dropdown and Multiple Select attributes. I'm pretty sure MSRP is a price type attribute. getAttributeText() eventually calls getOptionText() which returns false for regular attributes.

See Mage_Catalog_Model_Product::getAttributeText() and Mage_Eav_Model_Entity_Attribute_Source_Abstract::getOptionText()

Related Topic