Yii SQL Query To CGridview

CSqlDataProvider implements a data provider based on a plain SQL statement. This tutorial will help you to display the custom sql query result into cgridview as normal crud view. But dont forget to remove the semicolon in custom sql statement Because it will create error on count query.

Controller.php

<?php
...........
public function actionPending(){
$sql="SELECT * FROM ............";
$rawData = Yii::app()->db->createCommand($sql); 
$count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM (' . $sql . ') as count_alias')->queryScalar(); 
//the count
 $model = new CSqlDataProvider($rawData, array(
                   'keyField' => 'scyid',
                    'totalItemCount' => $count,
                    'sort' => array(
                        'attributes' => array(
                            'scyid', 'annual', 'admission_year_id', 'paid'
                        ),
                        'defaultOrder' => array(
                            'scyid' => CSort::SORT_ASC, //default sort value
                        ),
                    ),
                    'pagination' => array(
                        'pageSize' => 10,
                    ),
                ));
 
        $this->render('customsqlview', array(
            'model' => $model,
        ));
}
...........
?>

customsqlview.php

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'student-grid',
	'dataProvider'=>$model,
//	'filter'=>$model,
	'columns'=>array(
		array(
			'header'=>'S.Reg ID',
			'name'=>'scyid',	
		),
		array(
			'header'=>'Annual Amount',
			'name'=>'annual',	
		),
		array(
			'header'=>'Paid Amount',
			'name'=>'paid',	
			'value'=>'$data["paid"]==""?0:$data["paid"]',	
		),
		array(
			'header'=>'Year',
			'name'=>'admission_year_id',
			'value'=>'Yii::app()->list->yeartext($data["admission_year_id"])'
		),
		array(
            'class' => 'CButtonColumn',
            'template' => '{annual}',
            'buttons' => array(
                'annual' => array('url' => 'Yii::app()->createAbsoluteUrl("student/student/create",array("id"=>$data["scyid"],"tab"=>1))','label'=>'<span class="btn btn-xs red">Balance</span>'),
            ),
        ),
	),
)); ?>

Leave a Reply

Your email address will not be published. Required fields are marked *