Javanshir Mammadov Javanshir Mammadov - 1 year ago 60
PHP Question

Set language from menu

I want to change language (set locale) from menu. Translation module already configured. So the code for ex. :

$this->translate('Some Text', 'default', 'de_DE') ?>
is working. But I need to change language from menu. And I used Zend/I18n.

Answer Source

This is how I have implemented a language changed from a menu. You will need to install the Zend MvcTranslator component

public function changeLanguageAction()
{
    $language = $this->params()->fromRoute('lang', 'en');
    //CAN USE PHP setcookie() instead of this
    $this->cookieService->createCookie('xuage', $language, $this->getResponse()->getHeaders());
    //redirect to homepage
    $this->redirect()->toRoute('home');
}

Module.php

public function onBootstrap(Event $e)
{
    $app = $e->getParam('application');
    $em = $e->getApplication()->getEventManager();

    //Translation
    $this->initTranslator($e);
}

protected function initTranslator($event)
{
    $serviceManager = $event->getApplication()->getServiceManager();

    $lang = @$event->getRequest()->getCookie()->xuage;

    //if language is not set in the cookie, set the default language to english
    if (!$lang) {
        $lang = 'en';
    }

    $translator = $serviceManager->get('MvcTranslator');
    $translator
        ->setLocale($lang)
        ->setFallbackLocale('en');
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download