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!

4 Answers 4

4

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); } 
4

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.

3
  • "This way you have no unnecessary database queries." - what do you mean? is my answer below causing extra db queries? thanks Commented Jun 1, 2016 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. Commented Jun 1, 2016 at 20:19
  • works on magento2.4 👍 Commented Mar 25, 2021 at 9:41
2

Just use:

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

If you prefer using short-hand PHP:

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.