Joeri Verdeyen bio photo

Joeri Verdeyen

Web-engineer, cyclist, Nespresso lover, Strava pusher.

Twitter LinkedIn Instagram Github Stackoverflow Last.fm Strava

Change input name of form fields in Symfony2

Form field names in Symfony2

Symfony2 gives your input fields a name like this:

<input type="text" value="" name="update_personal[address]" id="update_personal_address">

In this case update_personal is the name of your form (type) you created.

What I wanted was this:

<input type="text" value="" name="address" id="update_personal_address">

Without doing too much magic or creating the form myself.

Solution

Return null in your getName implementation.

 1 class AddressType extends AbstractType
 2 {
 3 
 4     public function buildForm(FormBuilderInterface $builder, array $options)
 5     {
 6         ..
 7     }
 8 
 9     public function getName()
10     {
11         return null;
12     }
13 
14     ..

Extra

When you build your form in the controller (which I don’t recommend), you need to set the name of the root form to null.

1 $form = $this->get('form.factory')
2     ->createNamedBuilder(null, 'form', $address)
3     ->add('address', 'text');

Thanks for reading

Feel free to leave a comment if you have remarks or like this post