Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2- Dynamically change application language on Zend Framework 2

I'm using zend framework 2 and i'd like change the application language by clicking on a link for example.

this is my routing configuration :

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

and i'd defined en as default language :

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

on my module.php :

public function onBootstrap ($e) {

        $eventManager= $e->getApplication()->getEventManager();

        $routeCallback = function ($e) {
            $availableLanguages = array ('fr', 'en');
            $defaultLanguage = 'en';
            $language = "";
            $fromRoute = false;
            //see if language could be find in url
            if ($e->getRouteMatch()->getParam('lang')) {
                $language = $e->getRouteMatch()->getParam('lang');
                $fromRoute = true;

                //or use language from http accept
            } else {
                $headers = $e->getApplication()->getRequest()->getHeaders();
                if ($headers->has('Accept-Language')) {
                    $headerLocale = $headers->get('Accept-Language')->getPrioritized();
                    $language = substr($headerLocale[0]->getLanguage(), 0,2);
                }
            }
            if(!in_array($language, $availableLanguages) ) {
                $language = $defaultLanguage;
            }
            $e->getApplication()->getServiceManager()->get('translator')->setLocale($language);

        };

        $eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_ROUTE, $routeCallback);
    }

Now this works perfectly, but i want to let the user change the language just by clicking on link for example.

Any suggestion??

Thanks for any help !

like image 676
blackbishop Avatar asked Nov 11 '22 23:11

blackbishop


1 Answers

Maybe it's to late but here the solution to your question :

"Now this works perfectly, but i want to let the user change the language just by clicking on link for example."

you can do a menu in your navigation like this (using bootstrap)

<ul class="dropdown-menu">
                            <li><a href="<?= $this->url($this->route, array('lang' => 'fr'));?>">
                                <span class="flag fr"></span> Français
                            </a></li>
                            <li><a href="<?=$this->url($this->route, array('lang' => 'en'));?>">
                                <span class="flag gb"></span> English
                            </a></li>
                        </ul>

Assure that your po/mo/and other traduction file are matching the pattern "fr\en" etc...

And it will be work perfectly.

like image 84
Greco Jonathan Avatar answered Nov 15 '22 01:11

Greco Jonathan