问题1
我想通过ajax提交建立一个注册表.注册工作是$form-> isValid().但是,如果表单注册失败,我需要通过ajax返回这些错误.
if ($form->isValid()) {
}else{
$errors = $form->getErrors();
// return some json encoded errors here
}
$form-> getErrors()返回一个空数组,即使表单没有验证(在这种情况下我用一个太短的用户名进行测试).
问题2
我遇到的第二个问题是,如果表单验证但仍有错误.例如,某人尝试为其提交相同值的唯一字段.
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($form->getData());
$em->flush();
// error Could be a username submitted more than once,username is unique field
}else{
// ...
}
如何捕获该错误并通过json返回?
问题1
在表单构建器中,您可以使用error_bubbling将错误移动到表单对象中.指定字段时,将其作为选项传递,如下所示:
$builder->add('username','text',array('error_bubbling'=>true));
并且您可以像这样访问表单对象中的错误:
$form->getErrors();
输出类似的东西
array (
0 =>
Symfony\Component\Form\FormError::__set_state(array(
'messageTemplate' => 'Your username must have at least {{ limit }} characters.','messageParameters' =>
array (
'{{ value }}' => '1','{{ limit }}' => 2,),)),) [] []
fyi:如果您使用的是Form / Type,则无法将error_bubbling设置为默认值,必须将其分配给每个字段.
有用链接:http://symfony.com/doc/2.0/reference/forms/types/text.html#error-bubbling
问题2
http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html