@@ -421,22 +421,35 @@ via the ``request`` object::
421
421
public function indexAction(Request $request)
422
422
{
423
423
$locale = $request->getLocale();
424
-
425
- $request->setLocale('en_US');
426
424
}
427
425
426
+ To store the user's locale in the session you may want to create a custom event listener and set the locale there::
427
+
428
+ public function onKernelRequest(GetResponseEvent $event)
429
+ {
430
+ $request = $event->getRequest();
431
+ if (!$request->hasPreviousSession()) {
432
+ return;
433
+ }
434
+
435
+ // try to see if the locale has been set as a _locale routing parameter
436
+ if ($locale = $request->attributes->get('_locale')) {
437
+ $request->getSession()->set('_locale', $locale);
438
+ } else {
439
+ // if no explicit locale has been set on this request, use one from the session
440
+ $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
441
+ }
442
+ }
443
+
444
+ Read :doc: `/cookbook/session/locale_sticky_session ` for more on the topic.
445
+
428
446
.. note ::
429
447
430
448
Setting the locale using the ``$request->setLocale() `` method won't affect
431
449
rendering in the same action. The translator locale is set during the
432
450
``kernel.request `` event. Either set the locale before the listener is called
433
- (e.g. in a custom listener) or use the ``setLocale() `` method of the
434
- ``translator `` service.
435
-
436
- .. tip ::
437
-
438
- Read :doc: `/cookbook/session/locale_sticky_session ` to learn how to store
439
- the user's locale in the session.
451
+ (e.g. in a custom listener described above) or use the ``setLocale() `` method
452
+ of the ``translator `` service.
440
453
441
454
.. index ::
442
455
single: Translations; Fallback and default locale
0 commit comments