提交前验证表单

Validation of a form before submission

使用 Symfony 2.3 版及更新版本,我希望用户单击 link 以转到已存在实体的版本页面,并且显示的表单已经过验证,每个错误都与其对应的字段相关联,即我想要 在提交表单之前要验证的表单。

我关注了 this entry of the cookbook :

$form = $this->container->get('form.factory')->create(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
    ...
}

但是表单中没有填充实体数据:所有字段都是空的。我试图用 $myEntity 替换 $request->request->get($form->getName()),但它触发了异常:

$myEntity 不能用作 Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener 中的数组。php

有谁知道一种方法可以为提交方法提供格式正确的数据,从而实现我的目标?注意:我不想 Javascript 参与其中。

代替:

$form->submit($request->request->get($form->getName()));

尝试:

$form->submit(array(), false);

您需要将请求绑定到表单,以便使用提交的值填写表单,方法是:$form->bind($request);

这里详细解释了您的代码应该是什么样子:

//Create the form (you can directly use the method createForm() in your controller, it's a shortcut to $this->get('form.factory')->create() )
$form = $this->createForm(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));

// Perform validation if post has been submitted (i.e. detection of HTTP POST method)
if($request->isMethod('POST')){

    // Bind the request to the form
    $form->bind($request);

    // Check if form is valid
    if($form->isValid()){

        // ... do your magic ...

    }

}

// Generate your page with the form inside
return $this->render('YourBundle:yourview.html.twig', array('form' => $form->createView() ) );