0

Using twig, I would like to show a message on the frontend if a field is empty. My question refers to a date field, but I think this question could apply to other field types.

In my event content type I have smart_date field with unlimited cardinality. I do not want to make this a required field, but if the field is empty I want to show a message to visitors. Something like 'No dates are currently scheduled'.

I have created a template file called field--smartdate.html.twig and into this I have pasted the content of field.html.twig my base theme (Bootstrap). Copied below.

  {%
    set classes = [
      'field',
      'field--name-' ~ field_name|clean_class,
      'field--type-' ~ field_type|clean_class,
      'field--label-' ~ label_display,
    ]
  %}
  {%
    set title_classes = [
      'field--label',
      label_display == 'visually_hidden' ? 'sr-only',
    ]
  %}

  {% if label_hidden %}
    {% if multiple %}
      <div{{ attributes.addClass(classes, 'field--items') }}>
        {% for item in items %}
          <div{{ item.attributes.addClass('field--item') }}>{{ item.content }}</div>
        {% endfor %}
      </div>
      
    {% else %}
      {% for item in items %}
        <div{{ attributes.addClass(classes, 'field--item') }}>{{ item.content }}</div>
      {% endfor %}
    {% endif %}
  {% else %}
    <div{{ attributes.addClass(classes) }}>
      <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
      {% if multiple %}
        <div class="field--items">
      {% endif %}
      {% for item in items %}
        <div{{ item.attributes.addClass('field--item') }}>{{ item.content }}</div>
      {% endfor %}
      {% if multiple %}
        </div>
      {% endif %}
    </div>
  {% endif %}

I have read Checking for empty fields in Twig templates is complicated And, yes it does seem complicated and I am still unsure what to do.

I have also tried the Empty Fields module but I am hoping this can be done via the theme.

So what changes must I make to the code to display a message if the field is empty?

1 Answer 1

1

The fact that you are in the field template is proof for a non-empty field. So you need code outside of the field template to show a message. This can be PHP like the module you've linked or TWIG in a different template.

For example:

node.html.twig

{% if node.field_example.isempty %}
  <p>Field is empty</p>
{% endif %}

Your Answer

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

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