1
1
.. index ::
2
2
single: Sessions, saving locale
3
3
4
- Simulate old Behaviour of Saving the Locale
5
- ===========================================
4
+ Making the Locale "Sticky" during a User's Session
5
+ ==================================================
6
6
7
7
Prior to Symfony 2.1, the locale was stored in a session called ``_locale ``.
8
- Since 2.1, it is stored in the Request. You'll learn how to simulate the old
9
- way in this article.
8
+ Since 2.1, it is stored in the Request, which means that it's not "sticky"
9
+ during a user's request. In this article, you'll learn how to make the locale
10
+ of a user "sticky" so that once it's set, that same locale will be used for
11
+ every subsequent request.
10
12
11
13
Creating LocaleListener
12
14
-----------------------
13
15
14
16
To simulate that the locale is stored in a session, you need to create and
15
- register a new listener. The listener will look like the following, assuming
16
- that the parameter which handels the locale value in the request is called
17
- ``_locale ``::
17
+ register a :doc: `new event listener</cookbook/service_container/event_listener> `.
18
+ The listener will look something like this. Typically, ``_locale `` is used
19
+ as a routing parameter to signify the locale, though it doesn't really matter
20
+ how you determine the desired locale from the request::
18
21
19
22
// src/Acme/LocaleBundle/EventListener/LocaleListener.php
20
23
namespace Acme\LocaleBundle\EventListener;
@@ -39,9 +42,11 @@ that the parameter which handels the locale value in the request is called
39
42
return;
40
43
}
41
44
45
+ // try to see if the locale has been set as a _locale routing parameter
42
46
if ($locale = $request->attributes->get('_locale')) {
43
47
$request->getSession()->set('_locale', $locale);
44
48
} else {
49
+ // if no explicit locale has been set on this request, use one from the session
45
50
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
46
51
}
47
52
}
@@ -88,3 +93,11 @@ Then register the listener:
88
93
))
89
94
->addTag('kernel.event_subscriber')
90
95
;
96
+
97
+ That's it! Now celebrate by changing the user's locale and seeing that it's
98
+ sticky throughout the request. Remember, to get the user's locale, always
99
+ use the :method: `Request::getLocale<Symfony\\ Component\\ HttpFoundation\\ Request::getLocale> `
100
+ method::
101
+
102
+ // from a controller...
103
+ $locale = $this->getRequest()->getLocale();
0 commit comments