Yii Framework Forum: How to set up user-defined interface language for all site (i18n) - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How to set up user-defined interface language for all site (i18n) This tip shows how to save selected language between user requests Rate Topic: -----

#1 User is offline   umneeq 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 138
  • Joined: 10-October 11
  • Location:Russia

Posted 11 October 2017 - 01:08 PM

// 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(),
    ]
];

1

#2 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,184
  • Joined: 17-January 09
  • Location:Russia

Posted 14 October 2017 - 07:48 AM

https://github.com/s...ion-language.md
Yii 2.0 Development Cookbook

Enjoying Yii? Star us at github

Support me so I can work more on Yii: https://www.patreon.com/samdark
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users