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.
Have you tried attr
?
{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
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';
}
}
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'
)
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With