Accessing dynamic field names in Symfony’s TWIG using attribute and the tilde(~)

At last, a framework has finally given the tilde (~) a little respect. Hash tag (#) usually gets all the glory, but not this time!  Not is in this case.  Granted, the tilde might be happy to be used at all and chances are, this obscure solution to another view issue doesn’t mean tilde’s ready for primetime, but let’s show some respect when respect is due.  After all, without the tilde, you wouldn’t be able to dynamically create field names with string concatenation.

Symfony’s TWIG uses the tilde to help dynamically address or declare form fields.  This is handy if you have a bunch of form fields with hideous serialized numbers appended to them like “field_name_1” and “field_name_2″….  Without addressing all 50 of these, you can loop through them dynamically like so.  In this example, I only loop from 0 to 4.  An added bonus?  I check if the form field name exists.  That’s helpful in case you’re receiving form fields that are dynamically added and you don’t know how many possible form fields your antiquated form made, probably through some Javascript or using JQuery.

{% for i in 0..4 %}
   {% if attribute(form,'field_name_'~i) is defined %}
       {% for formItem in attribute(form,'field_name_'~i) %}
            
            {{ form_row(formItem) }}

       {% endfor %}
  {% endif %}

{% endfor %}

The only question is…. why didn’t you just use an array for those form fields?!  field_name[0], field_name[1] is much easier, but who am I to judge?

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *