2

I'v creatated a custom validator:

class MyValidator extends AbstractValidator
{
    const ERROR_CONST = 'error';

    protected $dbAdapter;
    protected $messageTemplates = array(
        self::ERROR_CONST => "Error msg for '%value%'."
    );

    public function __construct($dbAdapter)
    {
        $this->dbAdapter = $dbAdapter;
    }

    public function isValid($value, $context = null)
    {
        $this->setValue($value);
        /**
         * Do validation against db
         */

        if(/* Not valid */){
            $this->error(self::ERROR_CONST);
            return false;
        }
        return true;
    }
}

The validation work, I've been able to test it. What doesn't work is the output of the error message using

echo $this->formElementErrors($form->get('action'));

All that is outputted is an empty UL. Is this a translator issue? When I do a get_class on $this->getTranslator() in the validator I get the validator class name. When I var_dump $this->getTranslator() it outputs null. Do I need to set a translator for this to work and where would be the best place to set that translator so that it's system wide for my own validators?

Borje
  • 255
  • 5
  • 19

2 Answers2

2

Because you define a __construct method for your validator class, the parent __construct is not implicitly called: http://php.net/manual/en/language.oop5.decon.php (see the note)

You should modify your __construct method:

public function __construct($dbAdapter)
{
    $this->dbAdapter = $dbAdapter;
    //parent::__construct($options);
    parent::__construct(null); // or (void)
}

As you can see, $messageTemplates and $messageVariables are "loaded" from AbstractValidator::__construct, for being used in some methods ( error included):

https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/AbstractValidator.php#L73-L79

Gabriel
  • 73
  • 1
  • 2
  • 6
  • As simple as that. Sometimes you just need someone to point out the obvious. Thank you! – Borje Sep 27 '13 at 06:59
0

Maybe you forgot to add messageVariables ?

/**
 * Message variables
 * @var array
 */
protected $messageVariables = array(
    'value'  => 'value',
);
Remi Thomas
  • 1,528
  • 1
  • 15
  • 25
  • I don't use any variables except the value parameter. According to the docs it isn't needed to specify a messageVariables variable. But just to try it I want ahead an added it anyway, but still no luck. – Borje Sep 26 '13 at 14:36