Skip to content

Commit e36faec

Browse files
committed
feature #5099 Rebase of #4989 (solazs, weaverryan)
This PR was submitted for the 2.6 branch but it was merged into the 2.3 branch instead (closes #5099). Discussion ---------- Rebase of #4989 Just a PR after rebasing #4989, which had some extra commits. This will be committed to the 2.3 branch. Commits ------- 006303d Moving index down to correct section 7281c53 [#4989] Language tweaks and making the example simpler 1ad8122 Remove useless setLocale() call and add code block with locale setter 43b2098 Finaly touches on translation locale setting note 79f5865 Review note about setting the translator locale in a controller. 3b136c8 Update translation.rst
2 parents e5c28c8 + 006303d commit e36faec

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

book/translation.rst

+21-7
Original file line numberDiff line numberDiff line change
@@ -421,17 +421,28 @@ via the ``request`` object::
421421
public function indexAction(Request $request)
422422
{
423423
$locale = $request->getLocale();
424-
425-
$request->setLocale('en_US');
426424
}
427425

428-
.. tip::
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::
429429

430-
Read :doc:`/cookbook/session/locale_sticky_session` to learn how to store
431-
the user's locale in the session.
430+
public function onKernelRequest(GetResponseEvent $event)
431+
{
432+
$request = $event->getRequest();
432433

433-
.. index::
434-
single: Translations; Fallback and default locale
434+
// some logic to determine the $locale
435+
$request->getSession()->set('_locale', $locale);
436+
}
437+
438+
Read :doc:`/cookbook/session/locale_sticky_session` for more on the topic.
439+
440+
.. note::
441+
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.
435446

436447
See the :ref:`book-translation-locale-url` section below about setting the
437448
locale via routing.
@@ -512,6 +523,9 @@ in your application.
512523
Read :doc:`/cookbook/routing/service_container_parameters` to learn how to
513524
avoid hardcoding the ``_locale`` requirement in all your routes.
514525

526+
.. index::
527+
single: Translations; Fallback and default locale
528+
515529
Setting a default Locale
516530
~~~~~~~~~~~~~~~~~~~~~~~~
517531

0 commit comments

Comments
 (0)