ZF translation forms

262 views Asked by At

I'm working with ZF2 and I'm using the translator. In the config of my application I've added the translator to the service_manager factories, so it will be used by the ZF2 helpers.

This is how my translator config looks like:

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

In the module.php file of my application, I have the following piece of code in my onBootstrap method:

/**
 * Magic to determine the right locale to be used.
 * 
 * Check cookie
 * Check GET parameter
 * Check HOST (application can be used from several domain names)
 */ 

$translator = $serviceManager->get('translator');

// We have to change the current locale if $locale is not null.
if (!is_null($locale)) {          
    $translator->setLocale($locale);

    // The translate helper of the view has some problems with what we're doing.
    // So we'll manually add the translator with the correct locale to the view helper.
    $serviceManager->get('viewhelpermanager')->get('translate')->setTranslator($translator);
}

As you can see, I've already had some problems because of the locale modification in the onBootstrap method.

Now there are two things that can help me: - Help me to find a way to re-inject the correct translator into the form helper; - Help me to find a way to do this the way ZF2 likes or it should be done (My searches did not lead to a solution).

Hope you guys can help me out!

2

There are 2 answers

4
jchampion On

It should work the same way for the form helper.

$serviceManager->get('ViewHelperManager')->get('form')->setTranslator($translator);

EDIT

And use the MvcTranslator service instead of translator.

if (!is_null($locale)) {
    $translator = $serviceManager->get('MvcTranslator');
    $translator->setLocale($locale);
    // ...
}

If you do that, you should not even need the setTranslator() calls.

0
Khanh Van On

use MvcTranslator instead of translator:

$translator = $serviceManager->get('MvcTranslator');
$translator->setLocale($locale);
$serviceManager->get('ViewHelperManager')
               ->get('translate')->setTranslator($translator);