我想在我的 symfony2 表单上定义一个 id 属性。
我在我的树枝模板中尝试过这个:
{{ form_start(form, {'id': 'form_person_edit'}) }}
但它似乎不起作用。
你试过attr
吗?
{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
在传递给表单构建器的选项数组中注入 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(),
]);
}
或者在表单类型中:
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'
)
));