Difference between #1 and #2 of Serial Numbers (item counts) in GridView

unchanged
Title
Serial Numbers(item counts) in GridView
unchanged
Category
How-tos
unchanged
Tags
serial number, grid items count
changed
Content
Sometime we need to display numbers of items per page with their counting as a
serial number.

Here is How we can do it easily in Yii.

**Extend CGridColumn**


~~~
[php]
Yii::import('zii.widgets.grid.CGridColumn');
 
class CounterColumn extends CGridColumn {
 

}
~~~

We need to set starter value for the counter so, we have



~~~
[php]
    private $i = 0;
    public function init(){
        $pager=$this->grid->dataProvider->pagination;
        if($pager->currentPage==0){
            $this->i=0;
        }else{
            $this->i=$pager->currentPage*$pager->pageSize;
        }
        
    }
~~~

We need to use display the value, so we have 



~~~
[php]
    public function renderDataCellContent($row, $data) { 
 
        $this->i++;
 
        echo $this->i;
    }
~~~


Complete code is as 

~~~
[php]
Yii::import('zii.widgets.grid.CGridColumn');
 
class CounterColumn extends CGridColumn {
 
    private $i = 0;
    public function init(){
        $pager=$this->grid->dataProvider->pagination;
        if($pager->currentPage==0){
            $this->i=0;
        }else{
            $this->i=$pager->currentPage*$pager->pageSize;
        }
        
    }
    public function renderDataCellContent($row, $data) { // $row number is
ignored
 
        $this->i++;
 
        echo $this->i;
    }
}
~~~
**Using**


~~~
[php]
$this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'categories-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		array(
                    'header'=>'Sr #',
                    'class'=>'CounterColumn'
                ),
		'id',
                'name',
		array(
                        'header'=>'Actions',
			'class'=>'CButtonColumn',
                )

)); 
~~~

~~~



Write new article