Search code examples
phpsymfonyoopformbuilder

How can I set the form name with Symfony formbuilder?


I am creating a form with Symfony formbuilder:

$options =  [
     'attr'   => array('class' => 'form-control',),
     'data' => $data,
       ];

 $formBuilder->add($name, $class, $options);

When I look now at my form then the field looks like this:

<input name="form[color]" value="#c651a8" class="form-control">

But I want to replace form[color] with 12345. The result I like to have is:

<input name="12345" value="#c651a8" class="form-control">

I tried different things like for example:

  $options =  [
           'attr'   => array('class' => 'form-control','name' => '12345',),
           'data' => $data,
           ];

or

  $options =  [
           'attr'   => array('class' => 'form-control'),
           'name' => '12345',
           'data' => $data,
           ];

But I could not find a solution.


Solution

  • If you use a FormType class implent the getName() method:

    public function getName()
    {
        return null;
    }
    

    If you build the form via the form factory service to the following:

    $formBuilder = $this->get('form.factory')
        ->createNamedBuilder(null);
    
    $options =  [
        'attr'   => array('class' => 'form-control',),
        'data' => $data,
    ];
    
    $formBuilder->add('12345', $class, $options);