Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend framework 2 : How to set locale globaly?

I have to change the locale dynamically depending which language the user wants.

I can set the locale in the Application/Module.php like this :

public function onBootstrap(MvcEvent $e)
{
    $translator = $e->getApplication()->getServiceManager()->get('translator');
    $translator->setLocale('hu_HU');
}

But, how can I do this in the controller, if I want to change languages ? I tried this, but after this I can change the locale only for this one request and not global.

$translator = $this->getServiceLocator()->get('translator');
$translator->setLocale('srb_SRB');
like image 998
sgleser87 Avatar asked Apr 11 '13 10:04

sgleser87


2 Answers

Set up the default locale at configuration level! See #61 of module.config.php from ZendSkeletonApplications Application Module

'translator' => array(
    'locale' => 'en_US',
)
like image 138
Sam Avatar answered Nov 12 '22 14:11

Sam


I had the same issue. In my user login module, I registered for MvcEvent on bootstrap:

use Zend\Mvc\MvcEvent;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\SessionManager;
use Zend\Session\Container as SessionContainer;
use \Zend\I18n\Translator\TranslatorInterface;

... 

public function onBootstrap(MvcEvent $event)
{
    // Get event manager.
    $eventManager = $event->getApplication()->getEventManager();
    $sharedEventManager = $eventManager->getSharedManager();
    // Register the event listener method. 
    $sharedEventManager->attach(AbstractActionController::class, 
            MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);
}

Then when that event comes, I set the locale based on info from the URL:

public function onDispatch(MvcEvent $event)
{
    $servicemanager = $event->getApplication()->getServiceManager();
    $lang = $event->getRouteMatch()->getParam('lang','jp-JP');

    $translator = $servicemanager->get(TranslatorInterface::class);
    if( $translator != null )
    {
        $translator->setLocale($lang);
    } 
    ...

In the end, this does not really make the locale global - instead, it just sets it for every request. The net effect is the same, from the code point of view - i.e., I don't have to set the locale on every controller.

Hope that helps.

like image 40
alex gimenez Avatar answered Nov 12 '22 13:11

alex gimenez