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 %}
{% 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.


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.

  • Ah, thanks Brad. How do I use that workaround with a global rather than an entry though? myGlobalSet.type and myGlobalSet.myField.type both generate errors. – Phil Gyford Oct 21 '15 at 17:01
  • Ahh, good point. Let me think on it. – Brad Bell Oct 21 '15 at 17:53

Try using BaseModel::getAttribute():

{% if myGlobalSet.getAttribute('myField') %}
{% 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.

  • Thanks, but if I do that I still get the same error. – Phil Gyford Oct 21 '15 at 15:53

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.