Using Yii2 GridView with Array of Data

I have an array:

$arr = ['ID' => 'A1', 'Description' => 'Item to be sold', ...]

      

In the controller:

$provider = new ArrayDataProvider([
'allModels' => $arr,
//'sort' =>['attributes' => ['ID', 'Description'],],
'pagination' => ['pageSize' => 5]
]);
$this -> render('index', ['provider' => $arr]);

      

In sight ( index.php

):

GridView::widget([
'dataProvider' => $provider,
]);

      

And there is no result on the page. Where is it wrong?

+3


source to share


1 answer


There are several bugs in the code.

1) $arr

should have the following structure:

$arr = [
    ['ID' => 'A1', 'Description' => 'Item to be sold'],
    ...
],

      

2) The parameters render

you passed $arr

instead $provider

should have:

$this->render('index', ['provider' => $provider]);

      

3) You skipped the instruction return

before render

:

return $this->render('index', ['provider' => $provider]);

      



Also, I don't recommend using spaces around the arrow.

4) You have not specified any columns in GridView

. You can add ID

and Description

like this:

GridView::widget([
    'dataProvider' => $provider,
    'columns' => [
        'ID',
        'Description',
    ],
]);

      

5) And finally, you don't echo on the GridView screen. Should be:

echo GridView::widget([...]);

      

or

<?= GridView::widget([...]) ?>

      

+5


source







All Articles