@@ -427,22 +427,35 @@ via the ``request`` object::
427
427
public function indexAction(Request $request)
428
428
{
429
429
$locale = $request->getLocale();
430
-
431
- $request->setLocale('en_US');
432
430
}
433
431
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
+
434
452
.. note ::
435
453
436
454
Setting the locale using the ``$request->setLocale() `` method won't affect
437
455
rendering in the same action. The translator locale is set during the
438
456
``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.
446
459
447
460
.. index ::
448
461
single: Translations; Fallback and default locale
0 commit comments