You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.
- create file common\components\languageSwitcher.php
<?php
/*
author :: Pitt Phunsanit
website :: http://plusmagi.com
change language by get language=EN, language=TH,...
or select on this widget
*/
namespace common\components;
use Yii;
use yii\base\Component;
use yii\base\Widget;
use yii\bootstrap\ButtonDropdown;
use yii\helpers\Url;
use yii\web\Cookie;
class languageSwitcher extends Widget
{
/* ใส่ภาษาของคุณที่นี่ */
public $languages = [
'EN' => 'English',
'JP' => 'Japanese',
'TH' => 'Thai',
];
public function init()
{
if(php_sapi_name() === 'cli')
{
return true;
}
parent::init();
$cookies = Yii::$app->response->cookies;
$languageNew = Yii::$app->request->get('language');
if($languageNew)
{
if(isset($this->languages[$languageNew]))
{
Yii::$app->language = $languageNew;
$cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => $languageNew
]));
}
}
elseif($cookies->has('language'))
{
Yii::$app->language = $cookies->getValue('language');
}
}
public function run(){
$languages = $this->languages;
$current = $languages[Yii::$app->language];
unset($languages[Yii::$app->language]);
$items = [];
foreach($languages as $code => $language)
{
$temp = [];
$temp['label'] = $language;
$temp['url'] = Url::current(['language' => $code]);
array_push($items, $temp);
}
echo ButtonDropdown::widget([
'label' => $current,
'dropdown' => [
'items' => $items,
],
]);
}
}
- open file common\config\main.php add
...
'bootstrap' => [
...
'languageSwitcher',
...
],
...
...
'components' => [
...
'languageSwitcher' => [
'class' => 'common\components\languageSwitcher',
],
...
],
...
- open file frontend\views\layouts\main.php
- add use common\components\languageSwitcher;
- include widget in your layout by <?= languageSwitcher::Widget() ?>
ภาษาไทย YII 2 Widget เปลี่ยนภาษา
Just stopped working
Thanks for your simple and easy Widget!
At one moment found that cookies are created, but not read.
Thanks to this article , it was possible to restore work. Just rewrite the init() function like this
public function init() { if( php_sapi_name() === 'cli' ) { return TRUE; } parent::init(); $languageNew = Yii::$app->request->get( 'language' ); if( $languageNew ) { if( isset( $this->languages[ $languageNew ] ) ) { Yii::$app->language = $languageNew; $cookie = new Cookie( [ 'name' => 'language', 'value' => $languageNew, 'httpOnly' => true, ]); \Yii::$app->getResponse()->getCookies()->add($cookie); } } elseif( \Yii::$app->getRequest()->getCookies()->has( 'language' ) ) { Yii::$app->language = \Yii::$app->getRequest()->getCookies()->getValue( 'language' ); } }
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.