create change language hyperlink

Hi, i wan to create hyperlink for user select language.

I create this action in site controller

public function actionLanguage($lang)


        Yii::$app->language = $lang;        

        return $this->redirect(Yii::$app->request->referrer);


It doesnt work, then i change

return $this->redirect(Yii::$app->request->referrer);


return $this->render('about');

and it work. So i think this language change only apply to current action, thats why redirect dont work.

How to make all page use the selected language?

Yes, exactly, you set language to current request. For saving language, for example, you can save it to cookie and load it through BootstrapInterface like this:

(this code get language from cookie and if not set from user browser otherwise)


namespace frontend\components;

use yii\base\BootstrapInterface;

use yii\base\Object;

class LanguageSelector extends Object implements BootstrapInterface


    public static $supportedLanguages = ['en-US', 'ru-RU'];

    public function bootstrap($app)


        $preferredLanguage = isset($app->request->cookies['language']) ? (string)$app->request->cookies['language'] : null;

        if (empty($preferredLanguage)) {

            $preferredLanguage = $app->request->getPreferredLanguage(self::$supportedLanguages);


        $app->language = $preferredLanguage;



And add to config:

return [

    'id' => 'app-frontend',

    'name' => 'Aydengo',

    'sourceLanguage' => 'ru-RU',

    'language' => 'en-US',

    'basePath' => dirname(__DIR__),

    'bootstrap' => [



        // frontend\components\CurrencySetter::className(),


    // ...


And here controller`s action example:

public function actionChangeLanguage() {

        $language = Yii::$app->request->post('language');

        $supportedLanguages = \frontend\components\LanguageSelector::$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,



        return $this->redirect(Yii::$app->request->referrer);


Hi, kinda busy lately, only now got time to try. Where should i create LanguageSelector class, because i get error Class ‘app\components\LanguageSelector’ not found.

I use yii basic. Right now i create a folder components and create LanguageSelector.php inside that folder and give namespace

namespace app\components;


'bootstrap' => [




give me error

Fatal error: Class ‘app\components\LanguageSelector’ not found,

I do it like this

'bootstrap' => [




'components' => [

       'languageSelector' => [

            'class' => 'app\components\LanguageSelector',



now it work fine, thx for help :D