68

I would like to define a id attribute on my symfony2 forms.

I've tried with this in my twig template:

{{ form_start(form, {'id': 'form_person_edit'}) }}

But it seems not working.

wonzbak
  • 7,734
  • 6
  • 26
  • 25

3 Answers3

136

Have you tried attr?

{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
SirDerpington
  • 11,260
  • 4
  • 49
  • 55
34

Inject the id in the options array that is passed into the form builder:

public function newAction(Request $request)
{
    // create a task and give it some dummy data for this example
    $task = new Task();
    $task->setTask('Write a blog post');
    $task->setDueDate(new \DateTime('tomorrow'));

    $form = $this->createFormBuilder($task, ['attr' => ['id' => 'task-form']])
        ->add('task', 'text')
        ->add('dueDate', 'date')
        ->add('save', 'submit', ['label' => 'Create Post'])
        ->getForm();

    return $this->render('AcmeTaskBundle:Default:new.html.twig', [
        'form' => $form->createView(),
    ]);
}

Or in a form type:

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('task')
            ->add('dueDate', null, ['widget' => 'single_text'])
            ->add('save', 'submit');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Acme\TaskBundle\Entity\Task',
            'attr' => ['id' => 'task-form']
        ]);
    }

    public function getName()
    {
        return 'task';
    }
}
jcroll
  • 6,875
  • 9
  • 52
  • 66
8

Besides, I should add to the above mentioned answers, that you can do it in your controller like this:

$this->createForm(FormTypeInterFace, data, options);

For a sample - i did this so:

$this->createForm(registrationType::class, null, array(
    'action' => $this->generateUrl('some_route'), 
    'attr' => array(
        'id' => 'some_id', 
        'class' => 'some_class'
    )
));
Stephan Yamilov
  • 605
  • 7
  • 14