30

How do I check if a field is blank? I thought it was something like

{% if article.articleImage is defined %}

Which in this case is testing an Assets field (and seems to work). Tried the same for a text field (in a Matrix row), and that doesn't work, as far as I can tell:

{{ if block.heading is defined }}
1

4 Answers 4

53

The answer depends on the field type.

Assets, Categories, Checkboxes, Dropdown, Entries, Matrix, Multi-select, Radio Buttons, Tags, and Users fields each will each appear to be non-empty, even if they don’t have a user-submitted value, because in each case, entry.myFieldHandle will still return something:

  • an ElementCriteriaModel object for Assets, Categories, Entries, Matrix, Tags, and Users fields
  • a MultiOptionsFieldData object for Checkboxes and Multi-select fields
  • a SingleOptionFieldData object for Dropdown and Radio Buttons fields

So for each of those field types, you will need to use the |length filter to determine if there is an actual value.

{% if not entry.myCheckboxesField|length %}

Also worth noting for Assets, Categories, Entries, Matrix, Tags, and Users fields: ElementCriteriaModel objects also have a total() function which can be used to speed up your template if all you need to know is whether any elements were selected, and you won’t be actually looping through them further down in the template. (|length actually fetches the elements first, and then returns the count of the results, but stores those elements internally in case they are going to be looped through later on. .total() runs a separate, much less expensive DB query, but the results won’t be cached internally for later use.)

{% if not entry.myCategoriesField.total() %}

Color, Date/Time, Lightswitch, Number, Plain Text, Rich Text, and Table fields will each return an empty value (null, an empty string/array, etc.) when there is no value, so each of those field types are safe to use with the is empty test:

{% if entry.myTextField is empty %}

This would also work:

{% if not entry.myTextField %}

In all cases, the |length filter will work as expected, so if you don’t want to remember this stuff, just use that.

0
12

If you have a peek through the Twig documentation, you'll come across the empty test.

{% if block.heading is empty %}
    {# ... #}
{% endif %}
7

Stuart's answer totally works. You can also use Twig's length filter:

{% if article.articleImage|length %}
1

Well this documentation helped me a lot to check any conditions. It might help others too.

https://straightupcraft.com/articles/how-to-check-if-a-variable-or-value-exists-using-twig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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