Bor*_*ger 15 forms validation unique symfony
我有一个Customer实体,它只有一个唯一的电子邮件字段.我正在尝试编辑客户的电子邮件,验证工作正常.但是我在我的控制器中有这个:
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(),
));
}
Run Code Online (Sandbox Code Playgroud)
var_dump返回一个空数组,但验证器设置一个唯一错误,$editForm->isValid()返回false.有没有办法在验证期间检查控制器中的特定错误,还能解释它返回空错误数组的原因吗?基本上,如果出现错误,我想提供"合并"选项.
编辑:这是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';
}
}
Run Code Online (Sandbox Code Playgroud)
和树枝模板:
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
这是我的验证:
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: ~
Run Code Online (Sandbox Code Playgroud)
好的,在这里找到了答案:
事实证明,每个表单子项都有其自己的单独错误。当执行 var_dump 时
$editForm->getChildren()['email']->getErrors()
Run Code Online (Sandbox Code Playgroud)
我得到:
array (size=1)
0 =>
object(Symfony\Component\Form\FormError)[531]
private 'message' => string 'A customer under that email address already exists' (length=50)
protected 'messageTemplate' => string 'A customer under that email address already exists' (length=50)
protected 'messageParameters' =>
array (size=0)
empty
protected 'messagePluralization' => null
Run Code Online (Sandbox Code Playgroud)
我仍然想知道如何确定错误是由于独特的冲突而不解析错误消息字符串。
| 归档时间: |
|
| 查看次数: |
32879 次 |
| 最近记录: |