I am learning Yii2. I have no experience with v1.
I have a site that I am trying to convert to Yii2 and I have a user table. I used gii to generate the model and CRUD. I also have the same for the school table. A user attends a certain school.
I wish to display the ‘first_name’ and ‘last_name’ of the current user on the main page for the site views/layouts/main.php somewhere. How do I get that information onto main.php? Where do I insert the code?
I wish to display the school that the current user attends. I will need to use the school model from the View action (and create & update) of the UserController. This seems like I need to define some relation? How/where?
Sorry for sounding dumb, but I cannot find answers online (probably just not searching the correct terms) and IRC is very quiet.
I am a total noob with Yii and just need a jumpstart
- To display the current user informations in a view :
<p><?= !Yii::$app->user->isGuest ? Yii::$app->user->getIdentity()->first_name : '' ?></p>
It check if the user is connected and next shows the first_name of the user (identity).
- If in your database you used innoDB and created the relations, the Gii generated the relations between the tables like this : (I suppose that there is a column school_id in the user table)
* @property School $school
class User extends ActiveRecord
public function getSchool()
return $this->hasOne(School::className(), ['id' => 'school_id']);
And next in your view you can access the school of the current user :
<p><?= !Yii::$app->user->isGuest && Yii::$app->user->getIdentity()->school ? Yii::$app->user->getIdentity()->school->title : '' ?></p>
It checks if the user is connected and if he attends a school, and next show the title of the school
Thanks for the quick response. It looks like you are assuming I have a logged in user. I do not yet. I am simply trying to figure out Yii.
So, say I wish to display the name of the user with ID=1 on some page of my site say main.php. How do I accomplish this? Where do I retrieve the record? Controller/Model/View?
I am just trying to understand how everything works with Yii 2 . I appreciate the tips.