我有一个客户实体,它只有一个唯一的电子邮件字段。我正在尝试编辑客户的电子邮件并且验证工作正常。但是我的 Controller 中有这个:
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。有没有办法在验证期间检查 Controller 中的特定错误,您还能解释为什么它返回空错误数组吗?基本上,如果出现错误,我想提供“合并”选项。
编辑:这是表单类型:
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';
}
}
还有 Twig 模板:
{% 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: ~
最佳答案
出于调试目的,如果您使用 Symfony 2,您可以使用 $form->getErrorsAsString()
而不是 $form->getErrors()
。*
引自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);
。第一个参数对应于 deep
,第二个参数对应于 展平
”(参见@Roubi的评论)
关于forms - Symfony2 : my form returns false from isValid() but empty array for getErrors() from unique constraint condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17658959/