开发者

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

开发者 https://www.devze.com 2023-03-20 21:16 出处:网络
I\'m using sfGuard plugin for Doctrine. I want to override the default error message for unique username.

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

精彩评论

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

关注公众号