mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-01 11:39:41 +08:00
Update output-data-providers.md
This commit is contained in:
@ -339,3 +339,61 @@ class CsvDataProvider extends BaseDataProvider
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Filtering Data Providers using Data Filters <span id="filtering-data-providers-using-data-filters"></span>
|
||||
|
||||
While you can build conditions for active data provider manually as described in
|
||||
[Filtering Data](output-data-widgets.md#filtering-data) and [Separate Filter Form](output-data-widgets.md#separate-filter-form)
|
||||
sections of data widgets guide, Yii has data filters that are very useful if you need flexible filter condtions.
|
||||
Data filters could be used as follows:
|
||||
|
||||
```php
|
||||
$filter = new ActiveDataFilter([
|
||||
'searchModel' => 'app\models\PostSearch'
|
||||
]);
|
||||
|
||||
$filterCondition = null;
|
||||
|
||||
// You may load filters from any source. For example,
|
||||
// if you prefer JSON in request body,
|
||||
// use Yii::$app->request->getBodyParams() below:
|
||||
if ($filter->load(\Yii::$app->request->get())) {
|
||||
$filterCondition = $filter->build();
|
||||
if ($filterCondition === false) {
|
||||
// Serializer would get errors out of it
|
||||
return $filter;
|
||||
}
|
||||
}
|
||||
|
||||
$query = Post::find();
|
||||
if ($filterCondition !== null) {
|
||||
$query->andWhere($filterCondition);
|
||||
}
|
||||
|
||||
return new ActiveDataProvider([
|
||||
'query' => $query,
|
||||
]);
|
||||
```
|
||||
|
||||
`PostSearch` model serves the purpose of defining which properties and values are allowed for filtering:
|
||||
|
||||
```php
|
||||
use yii\base\Model;
|
||||
|
||||
class PostSearch extends Model
|
||||
{
|
||||
public $id;
|
||||
public $title;
|
||||
|
||||
public function rules()
|
||||
{
|
||||
return [
|
||||
['id', 'integer'],
|
||||
['title', 'string', 'min' => 2, 'max' => 200],
|
||||
];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Data filters are quite flexible. You may customize how conditions are built and which operators are allowed.
|
||||
For details check API docs on [[\yii\data\DataFilter]].
|
||||
|
||||
Reference in New Issue
Block a user