How to set a CSS ID attribute to a Symfony2 form input

Olav picture Olav · Jun 12, 2013 · Viewed 20.7k times · Source

This question is similar to another question. There the solution for setting the CSS class was to add it into the 3rd parameter of a call to FormBuilder::add():

->add('title', null, array('attr' => array('class'=>'span2')))

Unfortunately, this does not work for setting the CSS id. When I do

->add('title', null, array('attr' => array('id'=>'title-field')))

... this is ignored. The ID remains something like namespace_formtype_field.

How can I set the CSS ID, if at all?

Answer

mb3rnard picture mb3rnard · Jul 23, 2014

You can do it when you render your field in twig, if you set your id outside of the 'attributes' array like so:

{{ form_widget(form.field, { 'id': 'my_custom_id',  'attr': { 'class' : 'my_custom_class }} )}}