I have developed small ZF2 doctrine system for one of my client. All is good so far, but they require the system in 2 languages.
I can set default language as english or another language from my module/Application/config/module.config.php
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
And I also can use this method to set default in module.php
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$serviceManager = $application->getServiceManager();
// Just a call to the translator, nothing special!
$serviceManager->get('translator');
$this->initTranslator($e);
// Etc, more of your bootstrap function.
}
protected function initTranslator(MvcEvent $event)
{
$serviceManager = $event->getApplication()->getServiceManager();
// Zend\Session\Container
$session = New Container('language');
$translator = $serviceManager->get('translator');
$translator
->setLocale($session->language)
->setFallbackLocale('zh_CN')
;
}
This is good, now my system shows default language as Chinese. However, I would like to give option to users to choose from.
How do I do that?
I had found this link but I couldn't get it work.
When I add following function in Application/IndexController.php it doesn't do anything instead http://myurl.com/changeLocal throw 404 error. Do I need to add anything in module.config.php too?
public function changeLocaleAction()
{
// New Container will get he Language Session if the SessionManager already knows the language session.
$session = new Container('language');
$language = $request->getPost()->language;
$config = $this->serviceLocator->get('config');
if (isset($config['locale']['available'][$language])) {
$session->language = $language;
$this->serviceLocator->get('translator')->setLocale($session->language);
}
}
After long battle, here is how I have achieved this. Special thanks to @Kwido and @Wilt for sending me to right direction (I have voted both of them up).
Application/config/module.config.php
Application/module.php
now in Application/src/Application/Controller/IndexController.php I have added two action to catch the session and set the language:
Now just add the link in
layout.phtmlto have language switcher:Hope this helps others in future.