Reputation: 32640
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!
Upvotes: 3
Views: 2965
Reputation: 402
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
Upvotes: 6
Reputation: 1370
The way you have your route setup you will always have to include the lang parameter to access anything other than the default controller.
URL: '/' will have lang 'en' and controller 'default', etc. URL: '/es' will have lang value 'es' and controller 'default' URL: '/es/about' will have lang value 'es' and controller 'about' URL: '/about' will try to set lang to 'about' and probably break the route.
You can & should change the translator's language code in Module::onBootstrap. You will have access to the route parameters there through the MvcEvent object.
Upvotes: 1