Peach
Peach

Reputation: 19

choose language in the zend framework 2 website

I use the Zend/Translator to translate the text in my website. I set a default local and it works. Now the user should be able to choose the language in the layout.html:

...

<li class="dropdown">
   <a href="<?php echo $this->url('home');?>" class="dropdown-toggle" data-toggle="dropdown">Sprache<b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Deutsch</a></li>
          <li><a href="<?php echo $this->url('application/default', array('action'=>'en'));?>">Englisch</a></li>
          <li><a href="#">Französisch</a></li>
          <li><a href="#">Spanisch</a></li>
        </ul>
</li>

...

The default language is German. Now I try to change the language to English by choosing 'Englisch' in the dropdown-menu. But I don't know what to write in the controller. I tried it like this, but it doesn't work:

public function enAction()
{
    $translator = $this->getServiceLocator()->get('translator');
    $translator->setLocale('en');

    return $this->redirect()->toRoute('home');

}

Can someone help me?

Thanks.

Upvotes: 0

Views: 599

Answers (3)

Amin Arab
Amin Arab

Reputation: 530

when you want change language should have code to refresh page with append lang parameter to url . Setting is

class Settings{

   const DEFAULT_LANGUAGE = 'en';
   public static $locations = array(
    'sa'=>'sa_SA',
        'en'=>'en_US'
    );
}

and in Application\Module.php

public function onBootstrap(MvcEvent $e) {
    $lang = $e->getRequest()->getQuery('lang'); // new language
    $session = new Container('base');
    if($lang == null || $lang == ''){
        if ($session->offsetExists('lang')) {
            $lang = $session->offsetGet('lang'); // current language
        }else{
            $lang = 'en; // default language
        }
    }
    $session->offsetSet('lang', $lang);
    $loc = Settings::$locations[$lang];
    $translator
    ->setLocale($loc)
    ->setFallbackLocale(Settings::DEFAULT_LANGUAGE .'_' . Settings::DEFAULT_LOCATION);

}

Upvotes: 0

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

You can have a look at SlmLocale, a module that performs locale detection and storage (either via a session or cookie). With SlmLocale, you can render a menu to switch from locale, all urls are updated accordingly.

echo $this->localeMenu();

SlmLocale is capable of selecting a locale based on the hostname, part of the path (i.e. /en/my/url) or query parameter.

Disclaimer: I am the author of SlmLocale :)

Upvotes: 2

Exlord
Exlord

Reputation: 5381

the translator doesn't memorize the selected language when you set the locale. you need to keep the selected lang in session for future request. and in you modules bootstrap get the lang from session and set translators locale.

Upvotes: 0

Related Questions