How to translate form labels in Zend Framework 2?

僤鯓⒐⒋嵵緔 提交于 2019-11-28 10:12:18

Instead of using:

<?php echo $form->get('city')->getLabel(); ?>

You should use the formlabel view helper. This helper automatically uses your translator during rendering if you have inserted it in your ServiceManager. Most likely you will have it in your Application's module module.config.php:

'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
        ),
    ),

    'translator' => array(
        'locale' => 'en_US',
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
            ),
        ),
    ),

Once you do use the formlabel view helper:

echo $this->formLabel($form->get('city'));

And of course make sure your translations are in your .po file.

i think your problem is that you label are not detected by poedit (or similar tool), so you have to add them manually to your poedit catalogs (.po)

to make your label strings detected by tools like poedit, your strings need to be used inside a translate() function or _() (other function can be added in Catalog/properties/sources keyword)

as the _() function is not user in ZF2 (today) so a tiny hack is to add a function like this in your index.php (no need to modify anything, this way, in poedit params):

// in index.php
function _($str) 
{ 
    return $str; 
}

and in your code, just use it when your strings are outside of a translate function

//...
    $this->add(array(
        'name' => 'city',
        'type'  => 'Zend\Form\Element\Select',
        'options' => array(
            'label' => _('myLabel') ,    // <------ will be detected by poedit
            'value_options' => $this->cities,
            'id'  => 'searchFormCity',
        ),
    ));
//...

or like this if you prefer

$myLabel = _('any label string');  // <--- added to poedit catalog
//...
        'options' => array(
            'label' => $myLabel ,
            'value_options' => $this->cities,
            'id'  => 'searchFormCity',
        ),

@Ruben says right!

Me I use PoEdit to generate my *.mo files and to be sure to get all translations in the file, I create somewhere (in view for example) a file named _lan.phtml with all text to be translated :

<?php echo $this->translate("My label"); 
... ?>

Of course, Poedit has to be configured to find my keywords. check this to how to configure it

All solutions don't use the power of ZF2. You must configure your poedit correctly :

All things are here : http://circlical.com/blog/2013/11/5/localizing-your-twig-using-zend-framework-2-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!