64

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

我在我的树枝模板中尝试过这个:

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

但它似乎不起作用。

4

3 回答 3

128

你试过attr吗?

{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }}
于 2013-09-05T15:30:14.813 回答
30

在传递给表单构建器的选项数组中注入 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';
    }
}
于 2014-08-11T14:21:15.930 回答
6

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

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

对于一个样本 - 我这样做了:

$this->createForm(registrationType::class, null, array(
    'action' => $this->generateUrl('some_route'), 
    'attr' => array(
        'id' => 'some_id', 
        'class' => 'some_class'
    )
));
于 2016-02-05T08:31:07.217 回答