开发者

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

I'm using sfGuard plugin for Doctrine.

I want to override the default error message for unique username.

What I currently get is: "An object with the same "username" already exist.".

So, I tried doing this:

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

which didn't work开发者_开发技巧.

Then I also tried

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

and now I'm getting 2 errors outputed: mine and the default one.

How can i fix the second portion of the code in order to get only 1 message outputed?

Edit: http://trac.symfony-project.org/ticket/9426


Add this method to BaseDoctrineForm. Then, in your configure method (or anywhere esle) you can do:

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

The method:

/**
 * @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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜