Is there any way to redirect to a page other than login in behaviors method in Yii 2?
My behaviors method content:
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => AccessControl::className(),
'only' => [ 'create','update' ],
'rules' => [
[
'allow' => true,
'actions' => [ 'create'],
'roles' => ['@'],
],
[
'allow' => true,
'actions' => ['logout'],
'roles' => ['?'],
],
],
],
];
}
But it redirects to login. I need to specify another redirect page or call:
throw new \yii\web\HttpException(403, 'The requested Item could not be found.');
You need to change loginUrl
property of yii\web\User
class.
If you want to change it globally, edit your config:
'components' => [
'user' => [
'loginUrl' => ['site/sign-in'],
],
],
If you need to change it in the specific controller or action, you can also set it like this:
Yii::$app->user->loginUrl = ['site/sign-in'];
You need to override beforeAction()
method in controller where you need to do this. All access chesks are performed in this event.
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
// If you want to change it only in one or few actions, add additional check
Yii::$app->user->loginUrl = ['site/sign-in'];
return true;
} else {
return false;
}
}
For more details check official documentation about property and event.
You can benefit from denyCallback(), as Yii2
's official document defines it:
A callback that will be called if the access should be denied to the current user.If not set, denyAccess() will be called.
The signature of the callback should be as follows:
function ($rule, $action)
where $rule
is the rule that denies the user, and $action
is the current action object. $rule
can be null if access is denied because none of the rules matched.
As an example:
'denyCallback' => function($rule, $action) {
if ($something) {
//set flash for example
Yii::$app->session->setFlash('key', 'Value');
//Redirect
return $action->controller->redirect('action');
}
//as a default behavior, it throws an exception
throw new ForbiddenHttpException("Forbidden access");
},
I'm using yii2-user for user management, and the redirect to login was going to /user/login instead of the yii2-user defined /user/security/login. so my fix was to update the urlManager rules with: '' => 'user/security/'
I guess this could be used also to redirect to some other controller/action other than login.
See here.
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