How To Handle CGridview in Yii

CGridview Basic

Hint – For Html: When display the date, string, numbers without any html tags in cgridview, It will display properly. But in your text contains the html tage, You should have to add the type ‘raw’. Now you will get the encode string.
Hint – Conver Date Format: When you display the date in cgridview, You can convert the date format.
Hint – Condition: When display status like ‘Active’, ‘Inactive’ using 0 and 1, You can use condition in cgridview
Code:

<?php $this->widget('zii.widgets.grid.CGridView', array(
     'id'=>'user-grid',
     'dataProvider'=>$model->search(),
     'columns'=>array(
     array(
         'name'=>'username',
         'value'=>'$data->username',
     ),
     array(
         'name'=>'image',
         'type'=>'raw', // to encode html string
         'value'=>'$data->image',
     ), 
     array(
         'name'=>'createdon',
         'value'=>'date("Y-m-d",strtotime($data->createdon))',
        // or'value'=>'$data["createdon"]==""?"Not Set":date("Y-m-d",strtotime($data["createdon"]))',
     ), 
     array(
         'name'=>'isactive',
         'value'=>'$data["isactive"]==1?"Active":"Inactive"',
     ),
     array(
         'class'=>'CButtonColumn',
     ),
   ),
)); ?>

CGridview With User Methods

Hint – For Date Format Conversion: Database date format is “Y-m-d…” . But I need to display date “d-m-y” format in  CGridview and i will use the conversion in all cgridview . So I wrote common static function “dateformat()” in Datacomponent  class. When i send date to “dateformat” function It will return formated date.
Hint – Gridview To Model Functions: You can access the model function dynamically from gridview and display value using model response. create  “getStatus()” function in model and access it from gridview. See code.
Code:
Hint – Gridview To Anonymous Functions: You can create and access the function in gridview and display value using echo. See code.
Code:

<?php $this->widget('zii.widgets.grid.CGridView', array(
     'id'=>'user-grid',
     'dataProvider'=>$model->search(),
     'columns'=>array(
          array(
               'name'=>'username',
               'value'=>'$data->username',
          ),
          // Gridview To Component Method
          array(
               'name'=>'lasteditedon',
               // Access function of component class
               'value'=>'Datacomponent::dateformat($data->lasteditedon)',
          ), 
  
        // Gridview To Model Method
          array(
               'name'=>'status',
               // Html encode 
               'type'=>'raw',
               // Access function of model class
               'value'=>'$data->getStatus($data["fileid"])',
          ), 
          // Method Inside Gridview (Anonymous  Function)
          array(
               'header'=>'dob',
               'value'=>function($data) {
                           echo $data->dob;
               },
          ),
  
          array(
               'class'=>'CButtonColumn',
          ),
     ),
  )); ?>

CGridview Css Style

Hint – Change CGridview Table Style: CGridview Based on tables rows and colums. You can change the table styles. Just add class “gridtablecss” name to “itemCssClass”  properties next to columns array in CGridview. Now create stylesheet or modify the main stylesheet for table row, column, th, tr etc. Ex “gridtablecss.tr , gridtablecss td,  gridtablecss.th”. Now you table syles will change.
Code:

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->search(),
'columns'=>array(
),
'itemsCssClass'=>'gridtablecss',
)); ?>

CGridview CButtonColumn

Hint – Add More Buttons: CGridview have three buttons for actions. They are View, Update, Delete.  If we want Can add more buttons for actions. Now I will add one button for changing the status of user. The button name is “Status”.
Hint – More Button Options: For CGridview I gave more options from my experience.
Code:

<?php $this->widget('zii.widgets.grid.CGridView', array(
     'id'=>'user-grid',
     'dataProvider'=>$model->search(),
     'columns'=>array(
          array(
               'name'=>'username',
               'value'=>'$data->username',
          ),
          array(
               'class'=>'CButtonColumn',
               'templates'=>'{view}{update}{delete}{status}' // Added Status Button
               'buttons'=>array(
                    'status'=>array(
                         'label'=>'Activate',

                         'imageUrl'=>Yii::app()->request->baseUrl.'/images/status.png',
                         'url'=>'Yii::app()->createAbsoluteUrl(
                                      "user/status",
                                      array("id"=>$data->userid))',

                         'visible'=>'$data->status=="O"?TRUE:FALSE',
                         'options'=>array(
                              'class'=>'activatestatus',
                              'id'=>'user',
                              'title'=>'Click Here To Activate the User Status',
                        '),
                   ),
              ),
        ),
    ),
)); ?>

CGridview Ajax

Hint – Functions With Ajax: Ajax doing lot of works in CGridview. When you use update, delete in cgridview Ajax will helpful to update the gridview without page refresh. Here I gave some functions of ajax when cgridview updated.
Code:

<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
     'columns'=>array(   
          array( 
               'name'=>'username', 
               'value'=>'$data->username',
          ), 
          array( 'class'=>'CButtonColumn', 
               'templates'=>'{view}{update}{delete}',
               'afterDelete'=>'function(link,success,data){window.location.reload();}' ), 
          ),
          'afterAjaxUpdate'=>"function(){ }", 
   )); 
?>

CGridview EnableSorting

Using CGridview header column, We can change the result in ascending, descending order. In some situtation we would like to disable this type of action. To disable CGridview Header sorting use the following code

<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
      'enableSorting'=>false,
   )); 
?>

Images In CGridview

We can use the images as gridview column values. I gave the sample code below

<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
 'columns'=>array(    
  array(
            'name'=>'userimage',
            'type'=>'image',
            'value'=>'$data->userimage==""?Yii::app()->baseUrl."/images/default.png":Yii::app()->baseUrl."/images/userimage.png"',
        ),
      )
   )); 
?>

We can use the link in gridview column. I gave the sample code below


<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
     'columns'=>array(    
     array(
        'name'  => 'name',          
        'value' => 'CHtml::link($data->name,Yii::app()->createAbsoluteUrl("/user/view",array("id"=>$data->userid)))',
        'type'  => 'raw',
        ),
    )
)); 
?>

CGridview Summary Text

When you display the result in cgridview, the default summary text like “Displaying 1-1 of 1 result(s)”. To change or hide , using following code

Summary Text Values
{start} - Starting value of current showing result
{end}   - End value of current showing result
{count} - Total number of rows or result
{page}  - Current Page Number
{pages} - Total Pager Number
<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
      'summaryText'=>'',// hide
        //OR 
       //Displaying 1-1 of 1 result(s)
      'summaryText'=>'Displaying {start}-{end} of {page} result(s)',// text format change
   )); 
?>


Pagination Header Text And Override Pagination CSS

We can hide the pagination header text like “Go To Page:” in CGridview, CListview using pager option. We can change or replace the default pagination css using “cssFile” parameter of “pager”. Just give the css path for pager style.

<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
      'summaryText'=>'',// hide
      //'pager'=>array('header'=>''), // To override header text only
       'pager'=>array('header'=>'','cssFile'=>'/css/macropager.css'), // override header text,css
      
   )); 
?>

Empty Result Text

We can change the text when we get the no result of CGridview, CListview. We have to use the “emptyText” option to display empty text value

<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 
     'dataProvider'=>$model->search(),
      'summaryText'=>'',// hide
      'pager'=>array('header'=>''),
      'emptyText'=>'Coming soon..', // to display empty value

   )); 
?>

CGridview After Delete

When we delete the row from cgridvew, We can do some action on this delete action using afterDelete() method of yii.

<?php $this->widget('zii.widgets.grid.CGridView', array(
 'id'=>'regionmaster-grid',
 'dataProvider'=>$model->search(),
 'columns'=>array(
  'type',
  'name',
  
  array(
   'class'=>'CButtonColumn',
                        'template'=>'{update}{delete}',
                        'afterDelete'=>'function(link,success,data){
                               window.location.reload();
                        }',
                ),
         ),
    'itemsCssClass'=>'hastable',
)); ?>


Support Files

Component

<?php
class Datacomponent extends CApplicationComponent{
    public function init(){}

    static public function dateformat($date){
         $date=date('d-m-Y',strtotime($date));    
         return $date;
    }
}

CGridview Pagination Text

<?php $this->widget('zii.widgets.CListView', array(
 'dataProvider'=>$dataProvider,
    'summaryText'=>"<div class='whitesec_search'><p>{count} Full Quality Videos</p></div>",
 'itemView'=>'_viewvideo',
    'pager'=>array(
        'header'=>'PAGE',
        'cssFile'=>Yii::app()->theme->baseUrl."/css/pagination.css",
        'prevPageLabel'=>'',
        'nextPageLabel'=>'',
        'firstPageLabel'=>'',
        'lastPageLabel'=>'',
    ),
)); ?>

Column Header In CGridview

We can change the header of cgridview table in yii framework

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'email-grid',
	'dataProvider'=>$model->search(),
	'columns'=>array(    
		array(
            'name'=>'E-Mail',            
            'header'=>'email',
            'value'=>'$data->email',
            'htmlOptions'=>array(
                    'class'=>'email',
                ),
        ),
        ),
        ));         
?>

Row Selection Or Click Event In CGridView

We can do some action When we click on the table of cgridview of yii framework.

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'user-grid',
	'dataProvider'=>$model->search(),
	'summaryText'=>false,
	
	'selectableRows'=>1,
	'selectionChanged'=>'function(id){
			location.href = "'.Yii::app()->createAbsoluteUrl('user/view').
				'&id="+$.fn.yiiGridView.getSelection(id);
	}',	
	'columns'=>array(
		'user_id',
		'user_name',
	),
	'itemsCssClass'=>'table'
)); 
?>

Add Css Class To CGridView Table Row

‘rowCssClassExpression’ property of CGridView, is used for applying the class for table row.

  • $row : the row number (zero-based)
  • $data : the data model for the row
  • $this : the column object
<?php
	$this->widget('zii.widgets.grid.CGridView', array(
		'id'=>'user-grid',
		'dataProvider'=>$model->search(),
		//'filter'=>$model,
		'rowCssClassExpression' => '
			( $row%2 ? $this->rowCssClass[1]: $this->rowCssClass[0] )." ". ( $data->status=="OPEN"?"active":"inactive")
		',
		'columns'=>array(
		.............
		)
	));

Add Class Or Style For CGridView Header Cell

‘headerHtmlOptions’ is used to set properties like style, class etc of CGridView table header cell or column .

'columns'=>array(
..............
        array(
            'name'=>'username',
            'htmlOptions'=>array(..),// for table row columns
            'headerHtmlOptions'=>array(...), // for table header column style, css etc
        ),
..............

Add Css Class To CGridView Table Column

‘cssClassExpression’ or ‘htmlOptions’ are the properties of CGridView and it is used to apply the class for table cells.

<?php
	$this->widget('zii.widgets.grid.CGridView', array(
		'id'=>'user-grid',
		'dataProvider'=>$model->search(),
		//'filter'=>$model,
		'rowCssClassExpression' => '
			( $row%2 ? $this->rowCssClass[1]: $this->rowCssClass[0] )." ". $data->getmyclass()
		',
		'columns'=>array(
			..............
			array(
				'header'=>'Status',
				'type'=>'raw',
				'value'=>'"".$data->ticket->status.""',
				//'htmlOptions'=>array('class'=>'status'),
				'cssClassExpression'=>'"status"'
			),
			..............
		)
	));

This section will help you to display the ‘dropdownlist’ in ‘CGridView’ filter area. This type of search will make our search result fast.

<?php 
$month_list=array('1'=>'January','2'=>February);
$this->widget('zii.widgets.grid.CGridView', array(
	..................
	// method 1
	array(
		'name'=>'month_id',
		'value'=>'$data->month->name',
		'filter'=>array('1'=>'January','2'=>'February'),
	),
	// method 2
	array(
		'name'=>'year_id',
		'value'=>'$data->year->name',
		'filter'=>CHtml::listData(Month::model()->findAll(),
							'id',
							'month.yearname'
							),
	),
	// method 3
	array(
		'name'=>'month_id',
		'value'=>'$data->month->name',
		'filter'=>CHtml::activeDropDownList(
				$model,
				'month_id',
				CHtml::listData(Month::model()->findAll(),
					'id','name'),
		array('empty'=>'Select Month')),
	),
	// method 4
	array(
		'name'=>'year_id',
		'value'=>'$data->year->name',
        'filter'=>CHtml::dropDownList(
			'Modelname[year_id]',
			$model->month_id,
			CHtml::listData(Month::model()->findAll(),
					'id',
					'month.yearname'),
			array('empty'=>'Select Month')),
	),
	// method 5
	array(
		'name'=>'month_id',
		'value'=>function($data,$row) use ($month_list){
			return $month_list[$data->month_id];
		},	
		'filter'=>CHtml::activeDropDownList(
			$model,
			'month_id',
			$month_list,array('empty'=>'Select Month')),
	),
	..................
	));
?>	

CGridView Filter: Datepicker

I inserted the ‘CJuiDatePicker’ in a CGridView inline filter. We have to call one function using ‘afterAjaxUpdate’ attribute to activate the date picker, When we update the cgridview using ajax.

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'emp-reporting-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'afterAjaxUpdate' => 'reinstallDatePicker',
	'columns'=>array(
		array(
			'header'=>'User Name',
			'value'=>'$data->employee->username'
		),
		array(
			'name'=>'dob',
			'value'=>'$data->dob',
            'filter' => $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                'model'=>$model, 
                'attribute'=>'dob', 
            ), 
            true)
		)
	),
)); ?>

<?php
Yii::app()->clientScript->registerScript('ajax-update-date-picker', "
function reinstallDatePicker(id, data) {
    $('#EmpReporting_dob').datepicker();
}
");
?>