@@ -422,34 +422,27 @@ via the ``request`` object::
422
422
{
423
423
$locale = $request->getLocale();
424
424
}
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::
427
429
428
430
public function onKernelRequest(GetResponseEvent $event)
429
431
{
430
432
$request = $event->getRequest();
431
- if (!$request->hasPreviousSession()) {
432
- return;
433
- }
434
433
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);
442
436
}
443
437
444
438
Read :doc: `/cookbook/session/locale_sticky_session ` for more on the topic.
445
439
446
440
.. note ::
447
441
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.
453
446
454
447
.. index ::
455
448
single: Translations; Fallback and default locale
0 commit comments