Search code examples
phpdynamiczend-framework2localezend-translate

ZF2, I18n and dynamic locale not working anymore after update


After finally updating Apache 2.2 -> 2.4 and php 5.4 -> 5.5 translation in view is not dynamic anymore. My app is bilingual with english as fallback. The locale is set i.e. by user's profile using ::onBootstrap

class Module { public function onBootstrap($events) {

    $translator = $events->getApplication()->getServiceManager()->get(
        'translator'
    );

    $authSvc = $events->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');

    $locale = $this->getLocale($authService);

    $translator->setLocale(
        \Locale::acceptFromHttp($locale)
    );

}

After updating Apache and php, translation still works but translation in view uses the default locale from the system. If I put the locale in $this->translate('MY TXT', NAMESPACE, 'en_US') it works but this is not the point. Even after debugging, I could not identify the source of the problem. It worked the way it suppose to do more than 2 years before. Any help is welcome.


Solution

  • Found the problem. You have to set translator with locale to the view helper:

    public function onBootstrap($events)
    {
    
        ....
        $viewRenderer = $events->getApplication()->getServiceManager()->get('ViewRenderer');
    
        $plugIn = $viewRenderer->plugin('translate');
        $plugIn->setTranslator($translator, __NAMESPACE__);
        ...
    }
    

    Otherwise the locale is taken from the config.global if set there (as in my case). No idea why it worked before for so long...