gugoan
gugoan

Reputation: 780

How to use Yii::$app->language

I'm hard to know what is the ideal place to use the **\Yii::$app->language = 'pt';**

I tried in main.php view, but only the menu got the translation. In the tutorial-i18N says:

You may set the application language at runtime to the language that the user has chosen. This has to be done at a point before any output is generated so that it affects all the output correctly. Therefor just change the application property to the desired value

My intention is to store the desired language in a LANGUAGE field in the user profile (along with FULL_NAME, etc.).

In the code, I need to know the correct location and how to use the same.

EDIT

@Timothée Planchais, this way works:

class SiteController extends Controller
{
        public function init()
        {
        parent::init();

        if(!Yii::$app->user->isGuest) {
                Yii::$app->language = Yii::$app->user->identity->profile->language;
        }
        }

But work only in SiteController

Upvotes: 0

Views: 2534

Answers (1)

To set the application language, edit the file config/web.php :

$config = [
    'id' => 'myapp',
    'name' => My App',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'language' => 'pt',//HERE
    ...
]

You can do all in a custom Controller class which should be extended by all your controllers. In the init() function :

namespace app\components;

class Controller extends yii\web\Controller
{
  public function init()
  {
    parent::init();

    if(!Yii::$app->user->isGuest) {
      Yii::$app->user->getIdentity()->language = Yii::$app->language;
    }
  }

}

SiteController for example :

class SiteController extends app\components\Controller
{
  ...
}

Upvotes: 1

Related Questions