从 symfony2 中的控制器添加字段特定错误 [英] Adding a field specific error from the controller in symfony2

查看:21
本文介绍了从 symfony2 中的控制器添加字段特定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 symfony 表单正在进行一些复杂的验证,我需要能够将错误分配给我的控制器中的特定字段.现在,我有这样的全局错误:

I have some complex validation going on with my symfony form, and I need to be able to assign an error to a specific field from my controller. Right now, I have global errors working like this:

$error = new formerror("There is an error with the form");
$form->addError($error);

但这会产生全局错误,而不是绑定到特定字段.

But that creates a global error, not one bound to a specific field.

有没有办法在我的控制器的特定字段上抛出错误?

Is there a way to throw an error on a specific field from my controller?

推荐答案

感谢 IRC 上的一些帮助(感谢 @fkrauthan!)我想出了一个答案.

Thanks to some help over IRC (thanks @fkrauthan!) I came up with an answer.

SF2 中的每个字段实际上都是表单的一个实例.您需要做的是访问该字段的表单对象,然后在其上添加错误.幸运的是,symfony 提供了一种获取嵌入表单/字段的方法.

Every field in SF2 is actually an instance of form. What you need to do is access the form object of the field, and add then error onto it. Thankfully, symfony provides a method to get an embedded form/field.

这是我的代码:

$error = new FormError("There is an error with the field");
$form->get('field')->addError($error);

正如一些人所指出的,您需要在文件顶部包含 FormError 类:使用Symfony\Component\Form\FormError;

As some people have pointed out, you will need to include the FormError class at the top of your file: use Symfony\Component\Form\FormError;

这篇关于从 symfony2 中的控制器添加字段特定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆