Search code examples
phpzend-frameworkzend-validatezend-translate

How to translate messages of a custom validator in Zend Framework?


I created a custom validator by extending Zend_Validate_Abstract to validate a CAPTCHA input regarding Zend_Captcha:

class My_Validate_Captcha extends Zend_Validate_Abstract {
  const CAPTCHA = 'captcha';

  protected $_messageTemplates = array(
    self::CAPTCHA => "'%value%' isn't the right solution"
  );

  protected $_id;

  public function __construct($captchaId) {
    $this->setId($captchaId);
  }

  public function setId($id) {
    $this->_id = $id;
    return $this;
  }

  public function getId() {
    return $this->_id;
  }

  public function isValid($value) {
    $this->_setValue($value);

    $captcha = new Zend_Captcha_Image();
    if(!$captcha->isValid(array('input' => $value, 'id' => $this->getId()))) {
      $this->_error(self::CAPTCHA);
      return false;
    }

    return true;
  }
}

It works fine with Zend_Filter_Input. As you can see, I defined an error message for the case the input value isn't valid.

Now I tried to translate this message into German in the same way I translated the other messages coming from Zend_Validate_* classes. I did this with Zend_Translate providing an array adapter.

return array(
  // Zend_Validate_Alnum
  'notAlnum'     => "'%value%' darf nur Buchstaben und Zahlen enthalten",
  'stringEmpty'  => "'%value%' Dieser Wert darf nicht leer sein",
  // ...
  // My_Validate_Captcha
  'captcha'      => "'%value%' ist nicht die richtige Lösung"
)

My problem is that the messages from Zend_Validate_* are translated as defined here, but the message from My_Validate_Captcha isn't translated. I get an empty message if 'captcha' is present within the translation array. If it isn't present, I get the english message defined in the validator class.

How can I achieve that the message from the custom validator is also translated using the same mechanism?


Solution

  • My problem was the encoding of the file which contains the translation array. German Umlauts were not encoded properly. I'm using UTF-8 now and everything works.

    Thanks for all your efforts.