Magento 1.9 Product Attribute – Safely Use getAttributeText

attributesmagento-1.7magento-1.9productproduct-attribute

If I call getAttributeText on a non existing attribute, eg:

$product->getAttributeText('some-non-existing-field');

I get the fatal error:

Fatal error: Call to a member function getSource() on a non-object

Which I can't even try-catch because its fatal.

Different magento stores have different attributes (And also different products got different attributes), so how can I access attributes in a safe way that even if they are undefined I won't get fatal (for example get null or empty string if non-existence)?

or as an alternative, how can I test if attribute exists first?

Thanks!

Best Answer

Given that the product is already loaded (including this attribute), you can use getData() instead of the magic getter to be able to use a dynamic attribute code:

$attributeCode = 'custom_attribute_code');

if ($_product->getData($attributeCode) !== null){
    echo $_product->getAttributeText($attributeCode);
}

This way you have no unnecessary database queries.

Related Topic