zend-framework2zend-routezend-translate

Dynamically change default route parameters in zend framework 2?


I need to change my language application dynamically. I have the folowing route configuration:

'route'    => '/[:lang[/:controller[/:action[/:id]]]][[/page/:page]]',

'defaults' => array(
'lang'     => 'en',
        ),

Is it possible to change the parameter 'lang' from my controller or from my Module.php (function onBootstrap). I don't know if I can use a globale variable or something similar.

'defaults' => array(
'lang'     => $my_variable,
        ),

If it is possible how can I change it ?

Thaks for your help!


Solution

  • I had a similar problem and figured it out, try:

    $e->getRouter()->setDefaultParam('lang', 'de_DE');
    

    I'm triggering this on MvcEvent::EVENT_DISPATCH (see update note below) with the use of a listener, but onBootstrap in Module.php should work too.

    Update:

    Ok, now I see that MvcEvent::EVENT_DISPATCH is too late for applying a default parameter to the Router. Especially when You're interested not only in passing the language via route, but also in having translatable routes (in conjunction with 'router_class'=>'Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack').

    So it should be on MvcEvent::EVENT_ROUTE:

    // applying a default language param to route
    $e->getRouter()->setDefaultParam('lang', 'de_DE');
    
    // Now detect the requested language or retrieve 
    // from matched route
    // $detectedLocale =...
    // ...
    
    // Retrieve the translator
    $sm->get('translator');
    
    // Apply detected locale to the translator
    $translator->setLocale($detectedLocale);
    
    // and now this apply the translator to the router
    // for translatable routes
    $e->getRouter()->setTranslator($translator);
    
    // but don't forget about
    // 'router_class'=>'Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack'
    // for translatable routes
    

    I see people saying, that You should do this in onBootstrap(), but IMVHO onBootstrap is TOO EARLY for retrieving a matched route, which is required for detecting the locale/language passed by the client in a route/url parameter.

    By saying "detecting the locale" I'm definitely not thinking about any dirty string operations on the url/query string, I'm thinking about a clean getParam() on the matched route.

    Related: http://framework.zend.com/manual/2.2/en/modules/zend.mvc.mvc-event.html