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.

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?

Aaron Belchamber has written 243 articles

Leave a Reply

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