Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id attribute on form tag symfony

Tags:

twig

symfony

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.

like image 301
wonzbak Avatar asked Sep 05 '13 15:09

wonzbak


3 Answers

Have you tried attr?

{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
like image 173
SirDerpington Avatar answered Oct 24 '22 02:10

SirDerpington


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';
    }
}
like image 36
jcroll Avatar answered Oct 24 '22 01:10

jcroll


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'
    )
));
like image 6
Stephan Yamilov Avatar answered Oct 24 '22 01:10

Stephan Yamilov