使用 Yii2 的 GridView 中的默认过滤器

2022-01-07 00:00:00 sorting filter php yii2 gridview

我不知道如何设置 GridView 的过滤器默认值.这意味着当页面加载时,它将加载具有我设置的特定条件的过滤器.

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

推荐答案

一个简单的方法是使用搜索模型.

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

我使用默认 Gii 生成的代码来解释方法

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

使用链接作为

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

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

这将添加一个过滤器,其中 id = 7 即在我的情况下,因为 id 是主键,只会列出一个用户

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

假设您希望始终应用过滤器而不在 url 中显示任何内容

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,
     ]);
}

这将创建一个过滤器,其中用户名包含字符串 'mid'

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

如果你想要更高级的过滤器

if you want more advanced filters

您可以在 UserSearch 类中编辑 search() 函数,那里用于填充数据和 ActiveDataProvider 的查询将可供您使用.假设您不想列出不活跃的用户.

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 ..

相关文章