PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Translating messages

Validate classes provide a setTranslator() method with which you can specify a instance of Zend_Translate which will translate the messages in case of a validation failure. The getTranslator() method returns the set translator instance.

<?php
$validator 
= new Zend_Validate_StringLength(array('min' => 8'max' => 12));
$translate = new Zend_Translate(
    array(
        
'adapter' => 'array',
        
'content' => array(
            
Zend_Validate_StringLength::TOO_SHORT => 'Translated \'%value%\''
        
),
        
'locale' => 'en'
    
)
);

$validator->setTranslator($translate);

With the static setDefaultTranslator() method you can set a instance of Zend_Translate which will be used for all validation classes, and can be retrieved with getDefaultTranslator(). This prevents you from setting a translator manually for all validator classes, and simplifies your code.

<?php
$translate 
= new Zend_Translate(
    array(
        
'adapter' => 'array',
        
'content' => array(
            
Zend_Validate_StringLength::TOO_SHORT => 'Translated \'%value%\''
        
),
        
'locale' => 'en'
    
)
);
Zend_Validate::setDefaultTranslator($translate);

Note

When you have set an application wide locale within your registry, then this locale will be used as default translator.

Sometimes it is necessary to disable the translator within a validator. To archive this you can use the setDisableTranslator() method, which accepts a boolean parameter, and translatorIsDisabled() to get the set value.

<?php
$validator 
= new Zend_Validate_StringLength(array('min' => 8'max' => 12));
if (!
$validator->isTranslatorDisabled()) {
    
$validator->setDisableTranslator();
}

It is also possible to use a translator instead of setting own messages with setMessage(). But doing so, you should keep in mind, that the translator works also on messages you set your own.

Zend Framework