Categories
Web Development

How to change the id for a form input in Symfony 5+

If you create your forms with classes in Symfony 5+ then changing the ID of the form fields is something you are not allowed to do apparently. LOL You can add/change the class and other attributes but not the id. For some reason Symfony ONLY lets you change the id inside the template. I don’t know why.

Yes I am serious

To start with what got me even interested in trying to use attr and row_attr is when I was messing around with some of my forms, I was copying and pasting and moving parts in the template. This lead to issues as I would miss pieces or get things wrong some how. So I started trying to do the whole thing inside the FormType definition class using the methods below.

It has been pointed out that some feel it is better to define class, id etc. in the template. But as I pointed out above, I had issues with that. So below is what I found.

What doesn’t work

If you are like me then you have probably tried changing the ID by using the attr or row_attr attributes of the Type right? That seems logical right?

These two methods  are not even consistent. First off row_attr only accepts some attributes, which ones I have no idea, it ignores placeholder and id apparently. So then I tried attr, it works with placeholder but ignores ID.

Makes sense right?

It sure would be nice if those didn’t ignore the values you sent to them wouldn’t it. This problem is nearly 10 years old. Later I may look over the code update it and do a PR.

If you are like me you are using Javascript to read hidden fields from the form for various reasons. Otherwise the standard naming of ID’s works flawlessly. I had not discovered this until I had this unique use case.

What does work

So it appears the only way to do this is inconsistentYou have to do it in the form rendering code inside the template. Like this

{{ form_row(registrationForm.ajaxString, { 'id': 'ajaxString'}) }}

You can also change/add other attributes this way, but you can ONLY CHANGE THE ID THIS WAY.

Otherwise Symfony takes it upon itself to name the field for you and ignore your request.

Dictating like…

It would be much easier and consistent if I could just add the ID in the FormType definition class instead of having to add it to the template. Class and other attributes can be added/changed like this, but not id. Just a little confusing that is all.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.