且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 symfony2 中的控制器添加字段特定错误

更新时间:2023-11-19 18:49:52

感谢 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;