Yii2, GridView, save filters value in session

2019-08-11 00:24发布

问题:

Is there any solution to save filters (in session) so user can see "last used filters" when he come back?

Please link in manual or docs, or your code. I found nothing searching this question.

回答1:

This is somewhat a hack, but this saves filter, page and sorting for me.

Place this in your Controller, assuming your Model is called Customer:

    $searchModel = new CustomerSearch();

    $params = Yii::$app->request->queryParams;

    if (count($params) <= 1) {
      $params = Yii::$app->session['customerparams'];
      if(isset(Yii::$app->session['customerparams']['page']))
        $_GET['page'] = Yii::$app->session['customerparams']['page'];
      } else {
        Yii::$app->session['customerparams'] = $params;
    }

    $dataProvider = $searchModel->search($params);


回答2:

In the model Search class, at the beginning of search function add this code:

if (!isset($params["MyModelSearch"])) {
   if (isset(Yii::$app->session["mymodelsearch"])){
      $params["MyModelSearch"]=Yii::$app->session["mymodelsearch"];
   }
}
else{
   Yii::$app->session["mymodelsearch"]=$params["MyModelSearch"];
}


回答3:

In the model Search class, at the beginning of search function add this code:

if (!isset($params["MyModelSearch"])) {
 if (isset(Yii::$app->session["mymodelsearch"])){
  $params["MyModelSearch"]=Yii::$app->session["mymodelsearch"];
}
}
else{
   Yii::$app->session["mymodelsearch"]=$params["MyModelSearch"];
}

Hi, THank you for your solution. It works well with the value filter but not the sorting filter. How can we fix this?



回答4:

I can´t comment on Herbert Maschke code, I implemented it and worked well but then I dicovered that if I select an option of my gridview like Edit and then went back, filters keep their values and pagination too but in the next click on another page number, filters get lost. I made an improvement that worked for me.

$searchModel = new CustomerSearch();

$params = Yii::$app->request->queryParams;

if (count($params) <= 1) {
  $params = Yii::$app->session['customerparams'];
  if(isset(Yii::$app->session['customerparams']['page'])) <<------
    $_GET['page'] = Yii::$app->session['customerparams']['page']; <<------
  } else {
    Yii::$app->session['customerparams'] = $params;
}

$dataProvider = $searchModel->search($params);

It seems that only page parameter was recovered to $_GET (that later $_GET was used for pagination and lost all filters) so I changed those two lines:

if(isset(Yii::$app->session['customerparams'])) {
    $_GET = Yii::$app->session['customerparams'];