Browse Source

added docs about gridview filtering

tags/2.0.0-beta
Carsten Brandt 11 years ago
parent
commit
5985896ca4
  1. 65
      docs/guide/data-grid.md

65
docs/guide/data-grid.md

@ -192,3 +192,68 @@ Filtering data
-------------- --------------
- https://github.com/yiisoft/yii2/issues/1581 - 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

Loading…
Cancel
Save