Yii Framework Undefined Offset: 0

1.3k views Asked by At

I am trying to use CGridView with custom query, and trying to build a very simple with no sorting and stuff.

My View contains simple CGridView

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

And my controller passes the $dataProvider to the view

 $count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM ( ' . $query . ' ) as count')->queryScalar();
 $dataProvider=new CSqlDataProvider($query, array(
         'keyField' => false,
         'totalItemCount'=>$count,
         'pagination'=>array(
         'pageSize'=>10,
       ),
));

I don't have a keyField therefore I have set it to false. Moreover, I have tried printing out data using var_dump, data is present in the variable, but still I get this undefined offset error.

2

There are 2 answers

3
cetver On BEST ANSWER

You need to set the mapping for sorting.

/*
Query results
array(
    array(
        'id' => 1,
        'username' => 'username',
        'email' => 'email'
    ),
    ...
)
*/

return new CSqlDataProvider($query, array(    
    'keyField' => 'id', //required, any field from query results
    'totalItemCount'=> $count,
    'pagination' => array(
        'pageSize' => 10
    ),
    'sort' => array(
        'defaultOrder' => array(
            'username' => CSort::SORT_DESC,            
        ),
        'attributes' => array(
            'username', 
            'email',            
        ),
    ),
));
//grid.columns
array(
    array(
        'name' => 'id' //WO sort
    ),
    array(
        'name' => 'username', //with sort (isset in dp.sort.attributes)      
    ),      
)
1
Double H On

you have to provide keyfield other than false, change keyfield primary key of your query Table