Yii 1.1: Serial Numbers (item counts) in GridView

5 followers

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

Yii::import('zii.widgets.grid.CGridColumn');
 
class CounterColumn extends CGridColumn {
 
}

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

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

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

Complete code is as

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

$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',
        )
));

Total 3 comments

#16802 report it
chriscao at 2014/03/29 11:30pm
Good

'columns' => array( array( 'header'=>'No.', 'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)', ), ... )

It works well.

#10373 report it
PeRoChAk at 2012/10/23 02:13pm
Evgeniy Tkachenko

This is too good and more efficient

#10367 report it
YiiJeka at 2012/10/23 06:45am
Tip

And so I use in one line :)

'columns' => array(
    array(
      'header'=>'No.',
      'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
   ),
...
)

Leave a comment

Please to leave your comment.

Write new article