2

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!

3

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.

  • "This way you have no unnecessary database queries." - what do you mean? is my answer below causing extra db queries? thanks – Ronen Ness Jun 1 '16 at 14:36
  • I double checked, your solution is actually the same as getAttributeText() with an additional check, so it's fine. I thought it would load a single attribute from the database but apparently I was wrong. That makes our answers equally efficient. – Fabian Schmengler Jun 1 '16 at 20:19
  • but yours a little more elegant ;) thanks! – Ronen Ness Jun 1 '16 at 21:16
2

answering self:

https://tahiryasin.wordpress.com/2013/12/13/get-custom-attribute-value-in-magento/

$attribute = $_product->getResource()->getAttribute('custom_attribute_code');
if ($attribute)
{
    echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
2

Just use:

if($product->getCustomAttributeCode()) {
    echo $product->getAttributeText('custom_attribute_code');   
}
1

If you prefer using short-hand PHP:

echo $_product->getCustomAttributeCode()?$_product->getAttributeText('custom_attribute_code'):"";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.