Inserting Active Record Data into Yii's CGRidView widget

6.1k views Asked by At

I have a table in mysql that I want to display with the CGridView widget. Here is my code thus far:

My Controller file (snipped of course):

public function actionIndex()
{
  //call the AR table model
  $model = new ViewResults();
  //This generates a simple "SELECT * FROM table statment".
  $list = $model->findAll();
  $this->render('index', array('list'=>$list));
}

My View file looks like(snipped):

<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$list,
 )); ?>

I'm getting the following error:

Call to a member function getData() on a non-object in C:\xampp\framework\zii\widgets\CBaseListView.php on line 105

Here is the source code to the CBaseListView.php file.

I'm pretty sure I'm screwing up by putting the list object in the widget. Is there something I have to do to $list before I pass it to the widget?

3

There are 3 answers

4
Samuel Barbosa On BEST ANSWER

You can use the CActiveDataProvider Yii's Class. Something like this:

$dataProvider = new CActiveDataProvider('model', array(
  'criteria'=>array(
    'order'=>'column1',
  ),
));

$this->widget('zii.widgets.grid.CGridView', array(
  'id'=>'my-grid',
  'dataProvider'=>$dataProvider,
  'columns'=>array(
    'column1',
    'column2',
    'column3',
    array(
      'class'=>'CButtonColumn',
    ),
  ),
));

Where model is your model and columns your columns.

0
Neil McGuigan On

findAll() returns an array, whereas CActiveDataProvider returns a dataProvider.

If you want to use find all, all you have to do is convert the array using CArrayDataProvider

example:

<?
php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>new CArrayDataProvider($list, array()),
 )); 
?>
1
Samuel Barbosa On

Using CArrayDataProvider is also a option. But the sorting is easy to do when it comes from CActiveDataProvider.