简体   繁体   中英

redirect to another page after login in yii2

In Yii when you login by default it redirects to the index page. I want that when I will login to Yii the page will redirect to another page not the index page. So can anyone help me in this. Any help or suggestions will be highly appreciable.here is my actionLogin function in siteController.php

public function actionLogin()
{
    if (!Yii::$app->user->isGuest) {
        return $this->goHome();
    }

    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->goBack();
    }
    return $this->render('login', [
        'model' => $model,
    ]);
}

You can redirect to the page you prefere

  public function actionLogin()
  {
      if (!Yii::$app->user->isGuest) {
          return $this->goHome();
      }

      $model = new LoginForm();
      if ($model->load(Yii::$app->request->post()) && $model->login()) {
         return $this->redirect(['/admin/index']);
      }
      return $this->render('login', [
          'model' => $model,
      ]);
  }

or if need show an instance eg: the view for the id = $model->id

      public function actionLogin()
  {
      if (!Yii::$app->user->isGuest) {
          return $this->goHome();
      }

      $model = new LoginForm();
      if ($model->load(Yii::$app->request->post()) && $model->login()) {
         return $this->redirect(['/admin/view',  'id' => $model->id]);
      }
      return $this->render('login', [
          'model' => $model,
      ]);
  }

Here an example Open your views folder and open site folder and create a new page instead index.php ,just assume the new page is welcome.php and replace index by welcome in your controller like below

   public function actionLogin() 
{
 if (!Yii::$app->user->isGuest) 
{ 
return $this->goHome(); 
}
 $model = new LoginForm(); 
if ($model->load(Yii::$app->request->post()) && $model->login())
 {
 return $this->goBack(); 
}
 return $this->render('welcome', [ 'model' => $model, ]); 
}

change the login page as this

 public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(['site/loader']);
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

and in you controller in your case i think site controller add

public function actionLoader()
{
     return $this->render('yourPage');
}

hope that was helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM