Skip to content
Advertisement

zf2 change language dynamically

I have one question, about ZF2 Translator, in the specific case in the costruction the link for change langauge dunamically when user click on flag or menu link.

In My Application/config/module.config.php i have this code:

   'service_manager' => array(
        'factories' => array(
            'translator' => 'ZendI18nTranslatorTranslatorServiceFactory',
            'navigation' => 'ZendNavigationServiceDefaultNavigationFactory',
        ),

    ),

and my route is:

return array(
    'router' => array(
        'routes' => array(

            'home' => array(
                'type' => 'Segment',
                'options' => array(
                    'route'    => '/[:lang[/:action]]',
                    'constraints' => array(
                        'lang'   => '[a-zA-Z]*',
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'ApplicationControllerIndex',
                        'action'     => 'index',
                    ),
                ),
            ),

And in my Application/Module.php i set this code on bootstrap:

public function onBootstrap(MvcEvent $e)
    {
        $sm = $e->getApplication()->getServiceManager();

        $router = $sm->get('router');
        $request = $sm->get('request');
        $matchedRoute = $router->match($request);
        $params = $matchedRoute->getParams();

        if(isset($params['lang']) && $params['lang'] !== '') {
            $translator = $e->getApplication()->getServiceManager()->get('translator');
            //or
            //$translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');

            if($params['lang'] == 'en') {
                $translator->setLocale('en_US');
            }
        }

        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

now my route http://www.xxxx.com/it/index or http://www.xxxx.com/it/company but i can’t create a link in my view for change language in my application…

How do i proceed ?

Thanks

Advertisement

Answer

You can create a link to the same page you are in by changing only the lang parameter like the following:

$this->url(null, array('lang' => $anotherLang), array(), true)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement