预填表格数据

时间:2016-02-07 21:48:32

标签: forms symfony

我有一个使用Symfony2的表单。这是一段摘录:

$comment = new Comment();
$form = $this->createFormBuilder($comment)
    ->add('user_id', 'hidden')
    ->add('node_id', 'hidden')
    ->add('comment', 'textarea', [
        'attr' => [
            'style' => 'width:100%; background-color:inherit; color:white;',
                'rows' => '5'
            ]
        ])
    ->add('save', 'submit', ['label' => 'Send'])
    ->getForm();

(注意,这些只是一些领域,以保持简短。

然后我预先填写表格中的一些数据。

$form->get('user_id')->setData($user_id);
$form->get('node_id')->setData($video->getId());

但是当我加载页面并填写comment字段并提交时,我收到user_idnode_id尚未填写的错误。

我该怎么办?我该如何渲染它们?我可以使用这些预设值渲染它们吗?

1 个答案:

答案 0 :(得分:1)

嗯,这对我来说只是愚蠢,但我会拒绝我删除的冲动,而只是回答。

如果在控制器中设置值,请不要在表单中使用它们。

$comment = new Comment();
$comment->setNodeId($video->getId());
$comment->setUserId($user_id);

$form = $this->createFormBuilder($comment)
    ->add('comment', 'textarea', [
        'attr' => [
        'style' => 'width:100%; background-color:inherit; color:white;',
            'rows' => '5'
        ]
    ])
->add('save', 'submit', ['label' => 'Send'])
->getForm();

换句话说,只需直接在对象上设置值,然后将表单保留在其中。留下那些需要来自用户的值。

相关问题