Yii2从数组数据中过滤gridview

时间:2014-12-18 13:07:10

标签: gridview yii2

我遇到了下一个问题:我有一些数据阵列。我想用它创建带有过滤器的datagrid。我知道对于ActiveRecord模型,您想过滤的属性必须在rules()中是“安全的”。但如何使用数组中的信息?

$resultData = [
    '4' => [
        'id'          => 4,
        'key'         => 'dictionary_email',
        'value'       => 'Email',
        'description' => '//email comment'
    ],
    '5' => [
        'id'          => 5,
        'key'         => 'dictionary_username',
        'value'       => 'Name',
        'description' => '//name comment'
    ],
    '6' => [
        'id'          => 6,
        'key'         => 'dictionary_new-password',
        'value'       => 'New password',
        'description' => '//new password comment'
    ],
    '7' => [
        'id'          => 7,
        'key'         => 'dictionary_current-password',
        'value'       => 'Current password',
        'description' => '//current password'
    ],
];

我想使用此数据中的过滤器创建GridView。我的控制器:

$filtersForm = new FiltersForm;
if (isset($_GET['FiltersForm'])) {
    $filtersForm->filters = $_GET['FiltersForm'];
}
$resultData = $filtersForm->filter($resultData);

return $this->render('about', [
    'filtersForm' => $filtersForm,
    'resultData' => $resultData,
]);

我的观点:

$dataProvider = new ArrayDataProvider([
    'allModels' => $resultData,
    'sort' => [
        'attributes' => ['id', 'key', 'value', 'description'],
    ],
    'pagination' => [
        'pageSize' => 10,
    ],
]);

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel'  => $filtersForm,
    'layout'       => "{items}\n{pager}",
    'columns'      => [
        'id',
        'key',
        'value',
        'description',
    ],
]);

显示了DataGrid,但没有过滤器。

1 个答案:

答案 0 :(得分:0)

对于ArrayDataProvider,您可以使用相同的方式为属性指定过滤器(通过向模型的rules()方法添加属性)。

您也可以手动设置它,如果string此声明具有更高的优先级:

<?= GridView::widget([
    'columns' => [
        [
            'attribute' => 'description',
            'filter' => // ...
        ],
    ],
]) ?>