How to use Yii::$app->language

Guys, 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.

it doesn’t lie - put anywhere before output <_<

it means before render. controller or view. i personally would put it in controller, maybe even in base controller if your profile is accecible at any place

or in view main layout if you have one layout.

This way work fine:

class SiteController extends Controller


	public function init()



    	if(!Yii::$app->user->isGuest) {

        	Yii::$app->language = Yii::$app->user->identity->profile->language;



but I have to do in each CONTROLLER (ProductController, CategoryController, etc) in my application?

if you set profile this way it just depends where is your 1st request for it.

if you just set it for yii, than simply set it in one main layout file just before echoing it


Yii::$app->language = (!Yii::$app->user->isGuest && !empty(Yii::$app->user->identity->profile->language)) ?

    Yii::$app->user->identity->profile->language : Yii::$app->language;




if uyou use it in controllers than make your base controller and exend all your controllers from it with needed functionality.


Works fine!

I create a BaseController, and extended all controllers