Skip to content
Advertisement

Default Filter in GridView with Yii2

I don’t know how to set the filter default of GridView. It’s mean when page loaded, it’s will load the filter with specific condition that I’ve set.

Any idea for this? Thanks

Advertisement

Answer

A simple way to do this is by using the search model .

I am using Default Gii generated code to explain the ways

public function actionIndex()
{
     $searchModel = new UserSearch(); 
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

     return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
     ]);
}

Say you want a dynamic filter when the page is loaded

use the link as

../index.php?r=user/index&UserSearch[id]=7

This will add a filter where id = 7 ie in my case since id is the primary key only one user will be listed

Say if you want always apply a filter without showing anything in the url

public function actionIndex()
{
     $searchModel = new UserSearch(); 
     $searchModel->name = 'mid'; 
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

     return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
     ]);
}

This will create a filter where user’s name has string ‘mid’

if you want more advanced filters

you can edit the search() function in the UserSearch Class there the query used to populate the data and ActiveDataProvider will be available to you . say you do’t want to list users who are inactive .

    public function search($params)
    {
         $query = User::find();

         $dataProvider = new ActiveDataProvider([
             'query' => $query,
          ]);

         $this->load($params);
         $query->andFilterWhere(['active_status' => 1]);
         ....

this method will provide you with limitless ways to filter your results .. Hope this helps ..

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement