OK, I fixed the problem. So the answer to your question is : yes you need to do something more than just put those URL rules. You need to extend the UrlManager. Here’s my code :
namespace app\components;
use yii\web\UrlManager;
use Yii;
class ZUrlManager extends UrlManager
{
public function createUrl($params)
{
if (!isset($params['language'])) {
if (Yii::$app->session->has('language'))
Yii::$app->language = Yii::$app->session->get('language');
else if(isset(Yii::$app->request->cookies['language']))
Yii::$app->language = Yii::$app->request->cookies['language']->value;
$params['language']=Yii::$app->language;
}
return parent::createUrl($params);
}
}
In the config file, here’s the settings for the urlManager component :
'urlManager' => [
'class' => 'app\components\ZUrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<language:\w+>/<controller>/<action>/<id:\d+>/<title>' => '<controller>/<action>',
'<language:\w+>/<controller>/<id:\d+>/<title>' => '<controller>/index',
'<language:\w+>/<controller>/<action>/<id:\d+>' => '<controller>/<action>',
'<language:\w+>/<controller>/<action>' => '<controller>/<action>',
'<language:\w+>/<controller>' => '<controller>',
'<language:\w+>/'=>'site/index',
],
And for the sake of others, here’s my base controller class that all my other controllers extend (instead of extending directly the default controller class of the framework):
namespace app\components;
use Yii;
class Controller extends \yii\web\Controller
{
public function init()
{
parent::init();
// If there is a post-request, redirect the application to the provided url of the selected language
if (isset($_POST['language'])) {
$lang = $_POST['language'];
$MultilangReturnUrl = $_POST[$lang];
$this->redirect($MultilangReturnUrl);
}
// Set the application language if provided by GET, session or cookie
if (isset($_GET['language'])) {
Yii::$app->language = $_GET['language'];
Yii::$app->session->set('language', $_GET['language']);
$cookie = new \yii\web\Cookie([
'name' => 'language',
'value' => $_GET['language'],
]);
$cookie->expire = time() + (60 * 60 * 24 * 365); // (1 year)
Yii::$app->response->cookies->add($cookie);
} else if (Yii::$app->session->has('language'))
Yii::$app->language = Yii::$app->session->get('language');
else if (isset(Yii::$app->request->cookies['language']))
Yii::$app->language = Yii::$app->request->cookies['language']->value;
}
public function createMultilanguageReturnUrl($lang = 'fr_CA', $params = [])
{
if (count($_GET) > 0) {
$arr = $_GET;
$arr['language'] = $lang;
} else
$arr = array('language' => $lang);
$param_temp = [
$this->module->requestedRoute,
'language' => $arr['language'],
];
$params = array_merge($param_temp,$params);
$urlManager = Yii::$app->urlManager;
return $urlManager->createUrl($params);
}
}
Hope it will help someone that is struggling as I did on converting those instructions to yii 2.0.
I didn’t succeed yet converting to yii 2.0 the widget for selecting the language.