在不覆盖其他验证器的情况下更改post验证器的错误消息


Symfony - change error message of a post validator without overriding other validators?

我使用sfGuard插件的原则。

我想覆盖唯一用户名的默认错误信息。

我目前得到的是:"具有相同"username"的对象已经存在".

所以,我试着这样做:

$this->validatorSchema->getPostValidator('username')->setMessage('invalid', 'The username is already taken.');  

不工作

然后我也试了

$this->mergePostValidator(
  new sfValidatorDoctrineUnique(
    array(
      'model' => 'sfGuardUser',
      'column' => array('username'),
      'throw_global_error' => false
    ),
    array(
      'invalid' => 'The username is already taken.'
    )
  )
);

,现在我得到2个错误输出:我的和默认的。

我如何修复代码的第二部分,以便只输出1条消息?

编辑:http://trac.symfony-project.org/ticket/9426

将此方法添加到BaseDoctrineForm。然后,在您的configure方法(或其他任何地方)中,您可以这样做:

public function configure()
{
  $this->getPostValidatorUnique(array('username'))->setMessage('invalid', 'IN YOUR FACE');
}

方法:

/**
 * @param array $columns
 * @param sfValidatorBase $validator
 * @return sfValidatorDoctrineUnique
 */
public function getPostValidatorUnique($columns, $validator = null)
{
  if ($validator === null)
  {
    $validator = $this->getValidatorSchema()->getPostValidator();
  }
  if ($validator instanceof sfValidatorDoctrineUnique)
  {
    if (!array_diff($validator->getOption('column'), $columns))
    {
      return $validator;
    }
  }
  elseif (method_exists($validator, 'getValidators'))
  {
    foreach($validator->getValidators() as $childValidator)
    {
      if ($matchingValidator = $this->getPostValidatorUnique($columns, $childValidator))
      {
        return $matchingValidator;
      }
    }
  }
  return null;
}