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