// controller
/**
* @return \yii\web\Response
* @throws NotFoundHttpException
*/
public function actionChangeLanguage()
{
$language = Yii::$app->request->post('language');
$supportedLanguages = Yii::$app->params['supportedLanguages'];
if (!in_array($language, $supportedLanguages)) {
throw new NotFoundHttpException;
}
Yii::$app->language = $language;
$languageCookie = new Cookie([
'name' => 'language',
'value' => $language,
'expire' => time() + 60 * 60 * 24 * 30,
]);
Yii::$app->response->cookies->add($languageCookie);
return $this->redirect(Yii::$app->request->referrer);
}
// params
return [
// Add / remove languages here. The whole system will work.
// Format for locale installation: ll-CC, where ll is a two-letter or three-letter language code lowercase
// in accordance with ISO-639 (http://www.loc.gov/standards/iso639-2/),
// and CC is the country code in accordance with the standard ISO-3166 (https://www.iso.org/obp/ui/#search/code/).
'supportedLanguages' => [
'ru-RU' => 'ru-RU',
'en-US' => 'en-US',
],
];
// bootstrapper
namespace frontend\bootstrappers;
use yii\base\BootstrapInterface;
use yii\base\Object;
class LanguageSetter extends Object implements BootstrapInterface
{
public function bootstrap($app)
{
$preferredLanguage = isset($app->request->cookies['language'])
? (string)$app->request->cookies['language']
: null;
if (empty($preferredLanguage)) {
$preferredLanguage = $app->request->getPreferredLanguage(\Yii::$app->params['supportedLanguages']);
}
$app->language = $preferredLanguage;
}
}
// config
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => [
'log',
frontend\bootstrappers\LanguageSetter::className(),
]
];