Id attribute on form tag symfony

SymfonyTwig

Symfony Problem Overview


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.

Symfony Solutions


Solution 1 - Symfony

Have you tried attr?

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

Solution 2 - Symfony

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';
    }
}

Solution 3 - Symfony

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'
    )
));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwonzbakView Question on Stackoverflow
Solution 1 - SymfonySirDerpingtonView Answer on Stackoverflow
Solution 2 - SymfonyjcrollView Answer on Stackoverflow
Solution 3 - SymfonyStephan YamilovView Answer on Stackoverflow