简体   繁体   中英

How to get CGridView for the SQL Query result?

I try the following query, and which produces an array,

$user = Yii::app()->reg->createCommand()
->select('studentID')
->from('Students')
->queryAll();

But, when i try to get the value of the query in CGridview, Im getting the error,

Property "CDbCommand.0" is not defined.

here is the code for gridview,

$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'students-grid',
'dataProvider'=> new CSqlDataProvider($user),
));

EDITED: In Your $model define the data:

public function newsearch(){
$query = "Your Query";
$count=Yii::app()->db->createCommand($query)->queryScalar();
$dataProvider = new CSqlDataProvider($query, array(
         'totalItemCount'=>$count));
}

In your Controller Action:

$model = new model or assigned model;
 //Your Logic //
$this->render('viewname',array('model'=>$model));

And in your view file call this function:

'dataProvider'=> $model->newsearch(),

Remember your dataprovider attributes only depends on your query.Use alias and call in the gridview columns.

Take a look at CSqlDataProvider constructor , first param should be a string containing a SQL query, or a CdbCommand , but $user is an array .

You should try :

$command = Yii::app()->reg->createCommand()
  ->select('studentID')
  ->from('Students');

And :

'dataProvider'=> new CSqlDataProvider($command)

PS: did you try to use CActiveDataProvider ?

This is the code,

<?php 
$query = "SELECT student_name FROM  smartrea_srkreg.Students";
$count=Yii::app()->reg->createCommand($query)->queryAll();
$dataProvider = new CSqlDataProvider($query, array(
'totalItemCount'=>$count,
'pagination'=>array(
'pageSize'=>30,
 ),
));
var_dump($dataProvider);
?>

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

This is the content of the controller. Pass this dataprovider to the template

$dataProvider = new CActiveDataProvider('Students',
             array(
            'criteria'=>array(                        
            'select'=>'t.studentID'
        )));

In the template file paste the code below:

$this->widget('zii.widgets.grid.CGridView', array(
   'id'=>'subject-grid',
   'dataProvider'=>$model,
   'columns'=>array(
       'studetID',
        array(
           'class'=>'CButtonColumn',
        ),
   ),
));

May this help you :)

Use 'keyfield' to avoid the error, Undefined index 'id' and keyfield = name of the selected column

$dataProvider = new CSqlDataProvider($query, array(
'totalItemCount'=>(int) $count1,
'keyField' => 'studentID',
'pagination'=>array( 'pageSize'=>30, ),));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM