2

In a template, can I check whether a Global field exists, before I try to output its value? I want to ensure the page doesn't break entirely in the unlikely event of the field being removed from the CMS.

If I do:

{% if myGlobalSet.myField is defined %}
    Defined.
{% endif %}

then it works as expected; "Defined" isn't displayed if myField doesn't exist.

But if I have:

{% if myGlobalSet.myField is defined %}
    Defined. {{ myGlobalSet.myField }}
{% endif %}

I get:

Craft\GlobalSetModel and its behaviours do not have a method or closure named "myField".

if that field doesn't exist. It's like it's trying to process the field even though it's not defined.

Phil Gyford
  • 667
  • 1
  • 6
  • 17

2 Answers2

1

That's a known issue with Twig's is defined test. See here for an explanation and workarounds.

Note that this is no longer an issue in the upcoming Craft 3.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
0

Try using BaseModel::getAttribute():

{% if myGlobalSet.getAttribute('myField') %}
    Defined.
{% else %}
    Not defined.
{% endif %}

I was going to suggest BaseElementModel::getFieldValue() as the "proper" way, but that throws an exception if the field isn't found at all, so I think getAttribute() is your best bet.

Mike Pepper
  • 4,391
  • 17
  • 26