Yii2: BeforeAction is not setting Yii::$app->session->setFlash

Created on 3 Sep 2015  路  6Comments  路  Source: yiisoft/yii2

I have a controller where I have a beforeAction to check if a sessionVar is empty.

public function beforeAction($event)
{

   if (Yii::$app->session['activeProject'] == '') {
       Yii::$app->session->setFlash('error', "Please select first a project!");
       return $this->redirect(['/project']);
    }

    return parent::beforeAction($event);
}

If the var is empty it is redirecting to /project, but it does not show the flash message.
If I remove the

 return $this->redirect(['/project']); 

then it is displaying the flash on the view which is rendered by the action called.
Any ideas?

Most helpful comment

I think it's wrong to use return $this->redirect(..), because the return value will decide, whether the action should be performed or not (boolean). So in your case, even with the redirect, the action is executed, and then there's an immediate redirect afterwards. You should try it this way:

$this->redirect(...);
return false;

All 6 comments

Easy. You need to set the varriable to keep flash messages ubtil they get adked. Its a param.

Check yii 1.1.7 autoUpdateFlash param. Yii2 should have something similar. Couldnt find it now though. Otherwise it should become a feature request!

I am not talking about yii 1.1.7
This is the github for yii2.
It does not matter how yii1 handled things.
Yii2 is very different in many areas.

I think it's wrong to use return $this->redirect(..), because the return value will decide, whether the action should be performed or not (boolean). So in your case, even with the redirect, the action is executed, and then there's an immediate redirect afterwards. You should try it this way:

$this->redirect(...);
return false;

I know its yii2 and not yii1. But i was suggesting that you would look for a similar param/value that enables it.

@mikehaertl : thank you, that was the right answer.

Was this page helpful?
0 / 5 - 0 ratings