2
votes

I'm stuck with next problem: I have some array with data. I wanna create datagrid with filters from it. I know that for ActiveRecord models attributes that you wanna filtering must be 'safe' in rules(). But how to be with information from array?

$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'
    ],
];

I want to create GridView with filters from this data. My controller:

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

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

my view:

$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 is shown, but there is no filters.

1
See possible solution here - stackoverflow.com/questions/28428492/… - lubosdz

1 Answers

0
votes

For ArrayDataProvider you can specify filter for attribute the same way (by adding attribute to the rules() method of your model).

You can also set it manually and if it's string this declaration will have the higher priority:

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