@@ -428,34 +428,27 @@ via the ``request`` object::
428
428
{
429
429
$locale = $request->getLocale();
430
430
}
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::
431
+
432
+ To set the user's locale, you may want to create a custom event listener
433
+ so that it's set before any other parts of the system (i.e. the translator)
434
+ need it::
433
435
434
436
public function onKernelRequest(GetResponseEvent $event)
435
437
{
436
438
$request = $event->getRequest();
437
- if (!$request->hasPreviousSession()) {
438
- return;
439
- }
440
439
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
- }
440
+ // some logic to determine the $locale
441
+ $request->getSession()->set('_locale', $locale);
448
442
}
449
443
450
444
Read :doc: `/cookbook/session/locale_sticky_session ` for more on the topic.
451
445
452
446
.. note ::
453
447
454
- Setting the locale using the ``$request->setLocale() `` method won't affect
455
- rendering in the same action. The translator locale is set during the
456
- ``kernel.request `` event. Either set the locale before the listener is called
457
- (e.g. in a custom listener described above) or use the ``setLocale() `` method
458
- of the ``translator `` service.
448
+ Setting the locale using ``$request->setLocale() `` in the controller
449
+ is too late to affect the translator. Either set the locale via a listener
450
+ (like above), the URL (see next) or call ``setLocale() `` directly on
451
+ the ``translator `` service.
459
452
460
453
.. index ::
461
454
single: Translations; Fallback and default locale
0 commit comments