Yii 2.0: Language Selector

5 followers

common\components\LanguageSelector.php

<?php
namespace common\components;
 
use yii\base\BootstrapInterface;
use yii\web\Cookie;
use yii\base\Exception;
 
class LanguageSelector implements BootstrapInterface
{
    public $supportedLanguages = [];
 
    public function bootstrap($app)
    {
        $cookies = $app->response->cookies;
        $languageNew = $app->request->get('language');
 
 
        if($languageNew !== null)
        {
            if (!in_array($languageNew, $this->supportedLanguages)) {
                throw new Exception('Invalid your selected language.');
            }
 
                $cookies->add(new Cookie([
                    'name' => 'language',
                    'value' => $languageNew,
                    'expire' => time() + 60 * 60 * 24 * 30, // 30 days
                ]));
                $app->language = $languageNew;
                //echo 'test1';
 
        }
        else
        {
 
            $preferedLanguage = isset($app->request->cookies['language']) ? (string) $app->request->cookies['language'] : null;
 
            if(empty($preferedLanguage))
            {
                $preferedLanguage = $app->request->getPreferedLanguage($this->supportedLanguages);
            }
            $app->language = $preferedLanguage;
        }
    }
}

frontend/config/main.php in component section update bootstrp

'bootstrap' => ['log',
        [
            'class' => 'common\components\LanguageSelector',
            'supportedLanguages' => ['en-US', 'th-TH'],
        ]
    ],

in main layout of theme insert selector code

<?php
 echo Html::a('Th', Url::current(['language' => 'th-TH']));
 echo Html::a('En', Url::current(['language' => 'en-US']));
?>

reference: https://yii2-cookbook.readthedocs.org/i18n-selecting-application-language/

Total 1 comment

#19908 report it
Rohit Suthar at 2016/07/18 05:07am
Thanks for sharing

Thanks for sharing this, will try in my new projects.

Leave a comment

Please to leave your comment.

Write new article