I'm using the Yii 2 framework to build a custom app. My website is available both in english and french. Strings are being translated just fine, but I'm running into an issue when I wish to actually change the language from the UI.
Basically my website has two subdomains, one is en.domain.com
and the other being fr.domain.com
. If the user access one of those domains for the first time, my code detects the subdomain, sets the right language into Yii and creates a cookie to store the language code. If the user already had a cookie and access any of those subdomains, the code will use the cookie to set the language. If the user clicks on "FR" or "EN" to change the language, a JS script deletes the cookie and redirects to the other subdomain (basically the same flow of the first time he's on the website).
Now, the issue is that when the user tries to access the french (translated) version of the website for the first time, it doesn't work. The code is executed, the cookie is set (I can see it), but nothing is translated. However, when I refresh the page, it works just fine and everything is translated. Then if I switch between one and the other, it works well. It's always the first time (which is problematic, because when Google and users ask for the french version, it's still in english until they reload).
Here's a code snippet of my BaseController (all my controllers extends from this one, so this code is executed everytime the page loads):
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
/**
* Class BaseController
* @package app\components
*/
class BaseController extends Controller
{
public function init() {
parent::init();
// If no cookie
if (!isset($_COOKIE["language"])) {
$parsedUrl = parse_url(Yii::$app->HelperComponent->getUrl());
$host = explode('.', $parsedUrl['host']);
$subdomain = $host[0];
if ($subdomain == 'fr')
$code = "fr-CA";
else
$code = "en-US";
}
else {
$code = $_COOKIE["language"];
}
Yii::$app->language = $code;
setcookie("language", $code, time() + 31556926, '/');
}
}
Any idea what could cause this strange behavior? Thanks