我想在symfony2表单上定义一个id属性。
我在我的树枝模板中试过这个:
{{ form_start(form, {'id': 'form_person_edit'}) }}
但似乎没有用。
答案 0 :(得分:104)
您是否尝试过attr
?
{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
答案 1 :(得分:22)
在传递给表单构建器的options数组中注入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';
}
}
答案 2 :(得分:4)
此外,我应该补充上面提到的答案,你可以在你的控制器中这样做:
$this->createForm(FormTypeInterFace, data, options);
对于一个样本 - 我这样做了:
$this->createForm(registrationType::class, null, array(
'action' => $this->generateUrl('some_route'),
'attr' => array(
'id' => 'some_id',
'class' => 'some_class'
)
));