|
|
|
@ -192,3 +192,68 @@ Filtering data
|
|
|
|
|
-------------- |
|
|
|
|
|
|
|
|
|
- https://github.com/yiisoft/yii2/issues/1581 |
|
|
|
|
|
|
|
|
|
TBD |
|
|
|
|
|
|
|
|
|
For filtering data the GridView needs a [model](model.md) that takes the input from the filtering |
|
|
|
|
form and adjusts the query of the dataprovider to respect the search criteria. |
|
|
|
|
A common practice when using [active records](active-record.md) is to create a search Model class |
|
|
|
|
that extends from the active record class. This class then defines the validation rules for the search |
|
|
|
|
and provides a `search()` method that will return the data provider. |
|
|
|
|
|
|
|
|
|
To add search capability for the `Post` model we can create `PostSearch` like in the following example: |
|
|
|
|
|
|
|
|
|
```php |
|
|
|
|
<?php |
|
|
|
|
|
|
|
|
|
namespace app\models; |
|
|
|
|
|
|
|
|
|
use Yii; |
|
|
|
|
use yii\base\Model; |
|
|
|
|
use yii\data\ActiveDataProvider; |
|
|
|
|
|
|
|
|
|
class PostSearch extends Post |
|
|
|
|
{ |
|
|
|
|
public function rules() |
|
|
|
|
{ |
|
|
|
|
// only fields in rules() are searchable |
|
|
|
|
return [ |
|
|
|
|
[['id'], 'integer'], |
|
|
|
|
[['title', 'creation_date'], 'safe'], |
|
|
|
|
]; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public function scenarios() |
|
|
|
|
{ |
|
|
|
|
// bypass scenarios() implementation in the parent class |
|
|
|
|
return Model::scenarios(); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public function search($params) |
|
|
|
|
{ |
|
|
|
|
$query = Post::find(); |
|
|
|
|
|
|
|
|
|
$dataProvider = new ActiveDataProvider([ |
|
|
|
|
'query' => $query, |
|
|
|
|
]); |
|
|
|
|
|
|
|
|
|
// load the seach form data and validate |
|
|
|
|
if (!($this->load($params) && $this->validate())) { |
|
|
|
|
return $dataProvider; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
// adjust the query by adding the filters |
|
|
|
|
$query->andFilterWhere(['id' => $this->id]); |
|
|
|
|
$query->andFilterWhere(['like', 'title', $this->name]) |
|
|
|
|
->andFilterWhere(['like', 'creation_date', $this->creation_date]); |
|
|
|
|
|
|
|
|
|
return $dataProvider; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
Filtering by related columns |
|
|
|
|
---------------------------- |
|
|
|
|
|
|
|
|
|
TBD |
|
|
|
|