Hello!
I’m wondering how to deal with language setting of Yii, as my solution does not work completely.
Scenario:
My app has two languages - "en" and "bg". They could be "en_us" and "bg_bg", for simplicity I stick to the two-character codes.
I want all my URLs to be like /language-code/controller/action/param1/param2.
I had solved that by creating custom URL Manager Class:
'urlManager'=>array(
'class' => 'application.components.lang.MultiLanguageUrlManager',
'urlFormat' => 'path',
'rules' => array(
'<Language:\w{2}>/<controller:\w+>/<id:\d+>' => '<controller>/view',
'<Language:\w{2}>/<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<Language:\w{2}>/<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<Language:\w{2}>/gii' => 'gii',
'<Language:\w{2}>/gii/<controller:\w+>' => 'gii/<controller>',
'<Language:\w{2}>/gii/<controller:\w+>/<action:\w+>' => 'gii/<controller>/<action>',
)
And my URL Manager is:
class MultiLanguageUrlManager extends CUrlManager
{
public function parsePathInfo($pathInfo)
{
parent::parsePathInfo($pathInfo);
$urlLanguage = Yii::app()->getRequest()->getParam('Language');
$language = null;
if ($urlLanguage && in_array($urlLanguage, MultiLanguageUtil::getLanguageCodes()))
$language = $urlLanguage;
if (!isset($language) && isset($_COOKIE['Language']) && in_array($_COOKIE['Language'], MultiLanguageUtil::getLanguageCodes()))
$language = $_COOKIE['Language'];
if (!isset($language))
$language = $this->_defaultLanguage;
Yii::app()->setLanguage($language);
MultiLanguageUtil::setLanguageCookie($language);
$url = Yii::app()->getRequest()->getUrl();
preg_match('/^(?:\/)([a-z]{2})(?:\/)/', $url, $matches);
if (!isset($matches[1]) || !in_array($matches[1], MultiLanguageUtil::getLanguageCodes()))
Yii::app()->getRequest()->redirect('/' . $language . $url);
}
public function createUrl($route, $params = array(), $ampersand = '&')
{
if (!isset($params['Language']))
$params['Language'] = Yii::app()->language;
return parent::createUrl($route, $params, $ampersand);
}
}
The problem with the above solution is that the URL Manager does not seem to get called when I use modules!
So I’ve created an admin and users module, but can’t use them as they fallback to the default app language (en).
Any suggestions how to do it, something like a bootstrap file where to put the setting of Yii’s language?
Thank you!