2017-03-07 85 views
2

我想從菜單中更改語言(設置區域設置)。翻譯模塊已配置。因此,前者的代碼。 :$this->translate('Some Text', 'default', 'de_DE') ?>正在工作。但我需要從菜單中更改語言。我使用Zend/I18n。從菜單中設置語言

回答

1

這是我如何實現從菜單更改的語言。您需要安裝Zend MvcTranslator組件

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'); 
} 
+0

我試圖安裝MvcTranslator但我得到'模塊(Zend的\的mvc \ I18N)無法initialized.'錯誤消息 我添加了''Zend \ Mvc \ I18n','到modules.config.php 如你所說的改變Module.php和IndexController 我是否應該在module.config.php中更改smth? –

+0

你需要將它添加到composer.json並運行作曲家更新然後作曲家安裝 – code9monkey

+0

和最後一件事我的路由是這樣的: lang'=> [ 'type'=> Segment :: class, 'options '=> [ 'route'=>'/:lang', 'defaults'=> [ 'controller'=> Controller \ IndexController :: class, 'action'=>'index', 'lang' =>'en', ], ], ],' 但據我的理解,我需要改變它以及嗎? –