Yii2: How to add query params to searchModel of index action without affecting the filter model of the gridview
Asked Answered
U

2

5
$searchModel = new CustomersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

In Yii2, by default, we are provided with a searchModel and a dataProvider for the Index action. However, to customize the data returned so that it meets a specific criteria, I get a challenge. This is what I did:

$searchModel = new CustomersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->where('customers.status = 10');

This works fine but the problem is it interferes with the filterModel of the GridView such that searching anything from the provided search filters does not work on the data returned by the GridView. Is there a where in which I can add conditions to the searchModel without affecting the filterModel in the GridView?

Unexceptional answered 1/8, 2017 at 17:24 Comment(0)
T
11

If I understand correctly you want to allow users to use GridView filters but to limit the whatever results they've got to those that match customers.status = 10 condition. Is that right?

If you want not to reset the query conditions to the provided above but only to append it use andWhere like:

$dataProvider->query->andWhere('customers.status = 10');
Taxaceous answered 1/8, 2017 at 17:39 Comment(1)
Yes, you got my question right. I can't believe it was this simple. Let me test your solution and see how it goes. Thanks.Unexceptional
C
0

See a different between where and andWhere.

If you use where, andWhere does not work. If you want to filter multiple time use andWhere

Chimene answered 4/12, 2020 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.