YII2 : simple language Switcher Widget

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

  1. 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,
			],
		]);
	}

}
  1. open file frontend\views\layouts\main.php
    • add use common\components\languageSwitcher;
    • include widget in your layout by <?= languageSwitcher::Widget() ?>

ภาษาไทย YII 2 Widget เปลี่ยนภาษา

1 0
5 followers
Viewed: 31 695 times
Version: Unknown (update)
Category: Tutorials
Written by: phunsanit
Last updated by: phunsanit
Created on: Apr 26, 2015
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles