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
2
3
4
5
6
7
8
9
10
11
12
13
14
class AddressType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ..
    }

    public function getName()
    {
        return null;
    }

    ..

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
2
3
$form = $this->get('form.factory')
    ->createNamedBuilder(null, 'form', $address)
    ->add('address', 'text');

Thanks for reading

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