Reputation: 31
Why can't I pass a value from the controller to a view? The value is not null, but it seems that the value is not passed to the view page. Why?
Below is my code:
public function actionProfileuser()
{
$session = Yii::$app->session;
if($session['UserID'] == null){
Yii::$app->user->logout();
return $this->goHome();
}
else
{
//$model = User::find()->where(['ID'=>$session['UserID']])->all();
//$model = new User;
$model = (new \yii\db\Query())
->from('tbl_user')
->where(['ID' => $session['UserID']])
->all();
return $this->render('profileuser', [
'model' => $model,
]);
}
}
<?= $model->Name; ?>
Upvotes: 1
Views: 413
Reputation: 22174
You should use code similar to what is generated by Gii:
$model = User::findOne($session['UserID']);
if ($model === null) {
throw new ForbiddenHttpException('You are not authorized to view this page.');
}
It will fetch the User
model from the database and throw an exception if the requested user does not exist.
one()
or findOne()
does not guarantee that it will return non-null, so you need to check it yourself.
\yii\db\Query()
is for raw queries. It will not return you a model. In the best case you will get a query result as an array.
Upvotes: 0
Reputation: 133400
In your controller you retrieve a collections of
models, all()
. If you need just one, use one():
public function actionProfileuser()
{
$session = Yii::$app->session;
if($session['UserID'] == null){
Yii::$app->user->logout();
return $this->goHome();
}
else
{
//$model = User::find()->where(['ID'=>$session['UserID']])->all();
//$model = new User;
$model = (new \yii\db\Query())
->from('tbl_user')
->where(['ID' => $session['UserID']])
->one(); // <---------- use one()
return $this->render('profileuser', [
'model' => $model,
]);
}
}
<?= $model['Name']; ?>
Or using all, you should iterate over the modes. Fr showing all the results:
foreach( $model AS $key => $value){
echo $value->name;
}
Upvotes: 2