Drupal - Verify a field is not empty

Like I also wrote in How can you render fields from an entity reference in node templates? [Drupal 8], content is a render array that contains data prepared for displaying.

If you want to check or compare something, use the values instead, which are available on the node object.

{% if node.field_example.value %}.

Note that the property depends on the field type. If it's a reference field, you need to use target_id instead. The referenced question links to a entity field API cheat sheet that lists common field types and their properties.


You can't be sure about the structure of the render array inside of content, so this is possible not the best method.

This may be a better solution:

{% if content.field_example|render|striptags|trim %}
  <p>field is not empty</p>
{% endif %}

This checks if rendering the field generates any output.

But this depends, how you have configured the field format and what you try to do. For example, you could have configured to display a label if the field is empty. Then you have to adjust this. If you don't depend on the rendered output and only want to check, if the field has a value in the database, use the node object. See Berdir's answer.


{% if not (node.field_whatever.isEmpty == true) and content.field_whatever is defined %}
  <div class="whatever_markup">
    {{ content.field_whatever }}
  </div>
{% endif %}

This solution is quite bullet-proof and even working in reusealbe and/or shared templates (e.g. a shared node--teaser.html.twig accross multiple bundles) because

  • it works for all field types
  • it checks if the field exists
  • it checks if the field is not empty
  • it checks if the field is not hidden in display mode

The double negative not ...isEmpty == true is necessary, otherwise a non-existing field would fail the check. I also believe that my solution is much faster and resilient to errors than any check that involves rendering the field.

This should work for any entity template, e.g. you can simply replace node.field_xxx with paragraph.field_xxx in a paragraph.html.twig template file

Tags:

Theming

8