I've seen a number of requests for translatable error messages with
Zend_Validate and Zend_Filter_Input, and it was a major goal for
Zend_Form. While the latter's support is mostly complete, one major
issue was allowing injecting validator values into the messages.

I discussed this with Darby and Thomas, and I've now got a solution
committed to subversion.

Zend_Validate_Abstract now has the following methods:

  * setTranslator(Zend_Translate $translator = null)
  * getTranslator()
  * static setDefaultTranslator(Zend_Translate $translator = null)
  * static getDefaultTranslator()

Additionally, internally _createMessage() now checks to see if a
translator is registered (either globally or locally); if so, and the
translator has a translation for the given error code, it will translate
the message *and* do variable substitution.

How does it work?

Let's say you use the 'StringLength' validator. You could then define 
custom translations for the two error conditions:

    stringLengthTooShort = "The string %value% must be longer than %min% 
characters"
    stringLengthTooLong  = "The string %value% must be shorter than %max% 
characters"

Create your translation object:

    $translator = new Zend_Translate(...);

Then, in the easiest method, set your validator globally:

    Zend_Validate_Abstract::setDefaultTranslator($translator);

And, when you validate:

    // in this case, using Zend_Filter_Input:
    if (!$input->isValid()) {
        // messages are translated!
        $messages = $input->getMessages();
    }

You can also attach a translator to a single validation class instance:

    $stringLength->setTranslator($translator);

though that usage is less useful.

Only messages that have message keys in your translations will be
translated; otherwise, the original message string (or any that you've
set) from the validation object will be used.

I will be retro-fitting Zend_Form to utilize this functionality shortly.
In the meantime, if you use Zend_Validate or Zend_Filter_Input, this
works out-of-the-box for those of you tracking current svn.

Please test!

-- 
Matthew Weier O'Phinney
PHP Developer            | [EMAIL PROTECTED]
Zend - The PHP Company   | http://www.zend.com/

Reply via email to