表单 – Symfony2:我的表单从isValid()返回false,但是从唯一约束条件返回getErrors()的空数组

我有一个客户实体,它只有一个唯一的电子邮件字段.我正在尝试编辑客户的电子邮件,验证工作正常.但是我在控制器中有这个:
public function updateAction(Request $request,$id) {
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('AcmeDemoBundle:Customer')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Customer entity.');
    }


    $editForm = $this->createForm(new CustomerType(),$entity);
    $editForm->bind($request);
    if ($editForm->isValid()) {
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('ticket_result'));
    }
    var_dump($editForm->getErrors());

    return $this->render('AcmeDemoBundle:Customer:edit.html.twig',array(
                'entity' => $entity,'edit_form' => $editForm->createView(),));
}

var_dump返回一个空数组,但验证器设置唯一的错误,$editForm-> isValid()返回false.有没有办法在验证期间检查控制器中的具体错误,还可以解释为什么它返回一个空的错误数组?基本上,如果出现这个错误,我想提供“merge”选项.

编辑:这里是formtype:

namespace Acme\DemoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CustomerType extends AbstractType {


    public function buildForm(FormBuilderInterface $builder,array $options) {
        $builder
                ->add('email','email',array('required'=>true))
        ;

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\DemoBundle\Entity\Customer','cascade_validation' => true,));
    }

    public function getName() {
        return 'acme_demobundle_customertype';
    }
}

和树枝模板:

{% extends 'AcmeDemoBundle::layout.html.twig' %}
{% block body -%}
    <h1>Customer edit</h1>



  <form action="{{ path('customer_update',{ 'id': entity.id }) }}" method="post" {{ form_enctype(edit_form) }}>
        <input type="hidden" name="_method" value="PUT" />
        {{ form_widget(edit_form) }}
        <p>
            <button type="submit">Edit</button>
        </p>
    </form>

{% endblock %}

这是我的验证:

Acme\DemoBundle\Entity\Customer:
    constraints:
      - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: 
          fields: email
          message: "A customer under that email address already exists"

    properties:
        email:
            - Email: ~

解决方法

为了调试,您可以使用$form-> getErrorsAsString()而不是$form-> getErrors(),如果您使用Symfony 2. *

起价为this answer

$form->getErrorsAsString() should only be used to debug the form…it
will contain the errors of each child elements which is not the case
of $form->getErrors().

更新1:

“使用更新的Symfony版本,您必须使用$form-> getErrors(true,false);而第一个参数对应于深度和第二个平坦化(参见@Roubi的注释)

相关文章

HTML代码中要想改变字体颜色,常常需要使用CSS样式表。CSS是...
HTML代码如何让字体盖住图片呢?需要使用CSS的position属性及...
HTML代码字体设置 在HTML中,我们可以使用标签来设置网页中的...
在网页设计中,HTML代码的字体和字号选择是非常重要的一个环...
HTML(Hypertext Markup Language,超文本标记语言)是一种用...
外链是指在一个网页中添加一个指向其他网站的链接,用户可以...