Changes
Title
unchanged
Manage (Target) Language in Multilingual Applications + A Language Selector Widget (i18n)
Category
unchanged
Tutorials
Yii version
unchanged
Tags
unchanged
i18n, language, multilanguage, session, cookie, Widgets, behavior, event handler
Content
changed
I
f you haven case of a multilingual application,
you have to provide the usone might consider
wit
h a
mrea
ns to select/change the language, and you have to manage the application language in the background.
Here's my way of doing this (see also this [post](http://www.yiiframework.com/wiki/26/setting-and-maintaining-the-language-in-application-i18n/ "Setting Language") for an alternative):
- Provide a language selector in the header of each page using a custom widget.
- When a language is selected, save it in the Session and in a Cookie.
- Every time a page/url is requested, check if thesonable approach to store the preferred language of the user in a session variable, and after that, every time a page is requested, to check this session variable and render the page in the indicated language.
This tutorial shows a Yii-way of doing this.
<br>We implement an event handler for the _onBeginRequest_ event; as the name of the event suggests, this event handler will be called at the beginning of each request, so its a good place to check whether a language is provided (via
POSTpost, session or cookie) and set the application language accordingly.
<br>
For this,We also implement a
n event handler for the 'onBeginRequest' event. As the name of the event suggests, this event handler then will be called on the beginning of every request.
simple Language-Selector Widget, which can render the language options as ajax-links or as a drop-down list.
See also this [post](http://www.yiiframework.com/wiki/26/setting-and-maintaining-the-language-in-application-i18n/ "Setting Language") for an alternative.
#### _Why is it necessary to set the application language for every request?_
<br>--->The requested page will be shown in the _target language_ of the application, which can be set/get via `Yii::app()->language`.
<br>--->If this property is not set explicitly, Yii assumes it to be equal to the _source language_ of the application, which can be set/get via `Yii::app()->sourceLanguage` and defaults to `'en_us'`.
<br>--->These properties can also be set in the main config file, like
<br>`'sourceLanguage'=>'en',`
<br>`'language'=>'de',`[...]