Skip to content

Commit 65e39b1

Browse files
solazsweaverryan
authored andcommitted
Remove useless setLocale() call and add code block with locale setter
1 parent d38e3eb commit 65e39b1

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

book/translation.rst

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -427,22 +427,35 @@ via the ``request`` object::
427427
public function indexAction(Request $request)
428428
{
429429
$locale = $request->getLocale();
430-
431-
$request->setLocale('en_US');
432430
}
433431
432+
To store the user's locale in the session you may want to create a custom event listener and set the locale there::
433+
434+
public function onKernelRequest(GetResponseEvent $event)
435+
{
436+
$request = $event->getRequest();
437+
if (!$request->hasPreviousSession()) {
438+
return;
439+
}
440+
441+
// try to see if the locale has been set as a _locale routing parameter
442+
if ($locale = $request->attributes->get('_locale')) {
443+
$request->getSession()->set('_locale', $locale);
444+
} else {
445+
// if no explicit locale has been set on this request, use one from the session
446+
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
447+
}
448+
}
449+
450+
Read :doc:`/cookbook/session/locale_sticky_session` for more on the topic.
451+
434452
.. note::
435453

436454
Setting the locale using the ``$request->setLocale()`` method won't affect
437455
rendering in the same action. The translator locale is set during the
438456
``kernel.request`` event. Either set the locale before the listener is called
439-
(e.g. in a custom listener) or use the ``setLocale()`` method of the
440-
``translator`` service.
441-
442-
.. tip::
443-
444-
Read :doc:`/cookbook/session/locale_sticky_session` to learn how to store
445-
the user's locale in the session.
457+
(e.g. in a custom listener described above) or use the ``setLocale()`` method
458+
of the ``translator`` service.
446459

447460
.. index::
448461
single: Translations; Fallback and default locale

0 commit comments

Comments
 (0)