表单标签symfony上的Id属性

我想在我的symfony2表单上定义一个id属性。

我已经尝试过在我的树枝模板中:

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

但它似乎不工作。

你试过吗?

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

在传递到表单构build器的选项数组中注入id:

 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(), ]); } 

或者在表单中input:

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

此外,我应该加上上面提到的答案,你可以在你的控制器中这样做:

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

对于一个样本 – 我做到了这一点:

 $this->createForm(registrationType::class, null, array( 'action' => $this->generateUrl('some_route'), 'attr' => array( 'id' => 'some_id', 'class' => 'some_class' ) ));