【发布时间】:2011-02-10 12:50:20
【问题描述】:
我正在使用 sfGuardDoctrine 插件,我想自定义表单验证消息。
我怎样才能做到这一点?我在文档中找不到任何内容。
我发现的唯一方法是将 sfGuardValidatorUser.class 复制到 /apps/frontend/lib/validator 中,但我想知道是否有某种方法可以覆盖错误消息,而不是覆盖整个验证器。 .
【问题讨论】:
我正在使用 sfGuardDoctrine 插件,我想自定义表单验证消息。
我怎样才能做到这一点?我在文档中找不到任何内容。
我发现的唯一方法是将 sfGuardValidatorUser.class 复制到 /apps/frontend/lib/validator 中,但我想知道是否有某种方法可以覆盖错误消息,而不是覆盖整个验证器。 .
【问题讨论】:
我找到了一篇关于外部身份验证的帖子。在那里,作者创建了一个继承自原始插件表单的自定义表单。
我认为这是一种自定义所有内容(包括错误消息)的简洁方式。
链接:http://blog.honnecke.us/2010/01/using-sfdoctrineguardusers-external-authentication/
基本上,我们必须在 app.yml 中添加自定义表单的名称:
sf_guard_plugin_signin_form: sfGuardCustomFormSignin
然后我们在 app 文件夹的 lib/form 目录中创建表单:
class sfGuardCustomFormSignin extends sfGuardFormSignin
{
public function configure(){
parent::configure();
// custom code here
}
}
完成!
【讨论】:
如果只是您要自定义的现有验证消息,我已经看到了四个:
1 - failed username
2 - failed password
3 - failed username & password global error
4 - csrf attack after session timeout on form
前两个您可以直接在 plugins/sfDoctrinGuardPlugin/lib/form/doctrine 中自定义,就像对任何其他表单一样。
第三个我没有打扰/找到方法。
第四个可以这样写:Symfony 1.4: Custom error message for CSRF in forms
【讨论】:
奇怪的是,我想这样做并按照您发布的那样搜索 StackOverflow。
对于“普通”字段(例如名字、姓氏),使用 getValidator:
public function configure()
{
parent::configure();
...
// You may not need to set the field as true, depending on your sfDoctrineGuard schema
$this->getValidator('first_name')->setOption('required', true);
$this->getValidator('first_name')->setMessage('required', 'Please enter your first name');
}
对于 PostValidator 中的字段,可以在代码中更改消息:
public function configure()
{
parent::configure();
...
// Handle the email address error - more complicated than the rest
$pv = $this->validatorSchema->getPostValidator()->getValidators();
$pv[0]->setMessage('invalid', "Someone has already registered with this email address");
}
这里似乎没有一个容易遵循的逻辑......对于这个帖子验证器,我使用了以下内容:
public function configure()
{
parent::configure();
$this->validatorSchema->getPostValidator()->setMessage('invalid', 'Your email address or password is invalid');
}
我通过反复试验最终得到了这个结构,但它确实有效。 (现在我需要将验证器错误从“用户名”字段移动到全局错误)
This post 展示了如何设置默认消息来替换相当无用的默认 symfony 表单错误。
【讨论】: