我的验证看起来像
Acme\UserBundle\Entity\User:
constraints:
- \Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields:username, message: "Username already in use" }
- \Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields:email, message: "Email address already in use" }
properties:
username:
- NotBlank: ~
- MinLength: { limit: 2, message: "Your username must have at least {{ limit }} characters." }
email:
- Email:
message: The email "{{ value }}" is not a valid email.
checkMX: true
我的控制器如:
$form = $this->createForm(new RegistrationType());
$form->bindRequest($request);
if ($form->isValid()) {
//... save to db
}else{
$errors = $form->getErrors();
//... pass the errors back as json
}
我正在尝试构建通过ajax请求提交的用户注册控制器。但是,当触发验证错误时,$error
变量如下所示:
[2011-11-07 19:19:44] app.INFO: array (
0 =>
Symfony\Component\Form\FormError::__set_state(array(
'messageTemplate' => 'Email address already in use',
'messageParameters' =>
array (
),
)),
1 =>
Symfony\Component\Form\FormError::__set_state(array(
'messageTemplate' => 'Your username must have at least {{ limit }} characters.',
'messageParameters' =>
array (
'{{ value }}' => '1',
'{{ limit }}' => 2,
),
)),
) [] []
问题是我不知道错误对应哪个字段。有没有办法找到这些数据,这样当我发送json响应时,我可以将错误消息与相关字段相关联。
答案 0 :(得分:6)
我认为您可以单独查询每个字段,例如:
$form->get('username')->getErrors()
所以你可以这样建立一个数组:
$errors['username'] = $form->get('username')->getErrors();
$errors['email'] = $form->get('email')->getErrors();
您可以通过以下方式实现自动化:
$fields = $form->getChildren();
foreach ( $fields as $field ) {
$errors[$field->getName()] = $field->getErrors();
}
我认为getName
函数应该在自己的表单的子项上调用时返回字段名称。其他人可能会有更有效的方式......
答案 1 :(得分:3)
我认为已接受的答案已经过时,不再有SELECT tablesite.name,
tablesite.family,
tablesite.phone_number,
COUNT(action.service_provider_id)
FROM tablesite
LEFT JOIN action
ON tablesite.id_user=action.service_provider_id
AND action.vote !='' AND action.customer_comment =''
GROUP BY name, family, phone_number
方法了。
getChildren()
最后,如果您想要从生成的$errors = [];
foreach ($form->all() as $field) {
if ($field->getErrors()->count() > 0) {
$fieldName = $field->getName();
$errors[$fieldName] = [];
foreach ($field->getErrors() as $error) {
$errors[$fieldName][] = $error->getMessage();
}
}
}
访问表单字段,它会为您提供完整的输入字段名称:
FormView