Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Yii2 GridView with array of data

Tags:

php

yii2

I have an array:

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

In controller:

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

In view (index.php):

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

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

like image 496
mrrich Avatar asked Jan 07 '15 17:01

mrrich


1 Answers

There are few errors in your code.

1) $arr should have the structure like this:

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

2) In the render parameters you passed $arr instead of $provider, should be:

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

3) You missed return statement before render:

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

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

4) You did 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 are not echoing the GridView to the screen. Should be:

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

or

<?= GridView::widget([...]) ?>
like image 196
arogachev Avatar answered Oct 08 '22 16:10

arogachev