0

I would like to know how to check if a custom variation field has content in a twig template (commerce-product.html.twig with variations injected). I have tried with some filters and conditions but without success. I need to hide some html markup if the field is empty. For example:

{% if product.variation_field_mycustomfield is not empty %}
<div class="mycustomclass">My custom field: {{ product.variation_field_mycustomfield }}</div>
{% endif %}  

My products have some variations that users can select from a list. When this select changes, the product information must change, and some variations of the same product could have this field empty or not.

This question isn't related to only image fields. It's for any kind of field.

  • 3
    Does this answer your question? How to check if image field is empty? Using twig – Hudri May 27 at 16:34
  • This question is about commerce and variation types. Perhaps It works for nodes, but It doesn't work for variation types. I've tried it before posting this question. – briast May 28 at 8:49
1
  1. just vardump() the product.variation_field_mycustomfield that have an empty field then :
  2. then if it is an array :
{% if product.variation_field_mycustomfield|length == 0 %}
    <div class="mycustomclass">My custom field: {{ product.variation_field_mycustomfield }}</div>
{% endif %} 
  1. otherwise, if it is not an array and it is no empty but it has default value that is considered as empty:
{% if product.variation_field_mycustomfield == 'the vardump output you get at step1' %}
    <div class="mycustomclass">My custom field: {{ product.variation_field_mycustomfield }}</div>
{% endif %} 
| improve this answer | |

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.