@@ -422,34 +422,27 @@ via the ``request`` object::
422422 {
423423 $locale = $request->getLocale();
424424 }
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::
425+
426+ To set the user's locale, you may want to create a custom event listener
427+ so that it's set before any other parts of the system (i.e. the translator)
428+ need it::
427429
428430 public function onKernelRequest(GetResponseEvent $event)
429431 {
430432 $request = $event->getRequest();
431- if (!$request->hasPreviousSession()) {
432- return;
433- }
434433
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- }
434+ // some logic to determine the $locale
435+ $request->getSession()->set('_locale', $locale);
442436 }
443437
444438Read :doc: `/cookbook/session/locale_sticky_session ` for more on the topic.
445439
446440.. note ::
447441
448- Setting the locale using the ``$request->setLocale() `` method won't affect
449- rendering in the same action. The translator locale is set during the
450- ``kernel.request `` event. Either set the locale before the listener is called
451- (e.g. in a custom listener described above) or use the ``setLocale() `` method
452- of the ``translator `` service.
442+ Setting the locale using ``$request->setLocale() `` in the controller
443+ is too late to affect the translator. Either set the locale via a listener
444+ (like above), the URL (see next) or call ``setLocale() `` directly on
445+ the ``translator `` service.
453446
454447.. index ::
455448 single: Translations; Fallback and default locale
0 commit comments