class TestController extends Controller {
function init() {
if(!(strtolower(yii::$app->requestedRoute) == "account/login" || empty(yii::$app->requestedRoute)))
{
if (false===$this->isLogin()) {
return $this->redirect('/login'); //it works, will redirect
}
} else {
if($this->isLogin()) {
return $this->redirect('/purchaser/manifest'); //not work, won't redirect
//echo $this->redirect('/purchaser/manifest'); //work
}
}
}
}
I had overriden Controller. When I tried to do filter, I found this problem. I'm confused, any help?
From Yii2 docs:
In case the action should not run, the request should be handled inside of the
beforeActioncode by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
// your custom code here
//Eg
if(something){
$this->redirect('/login');
return false; //not run the action
}
return true; // continue to run action
}
Yii2 not care about return value of init() function. Applications will still continue to run action.
About redirect() function, It will not work until application completed (beforeAction return false or an action return). So when you call redirect() in init() function nothing happens.
But return $this->redirect('/login'); It works. Why? Because in this case, application redirect after run your action.
you can try, even write $this->redirect('/login'); It still works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With