CListView item index

v.1.1.6

Hi guys!

Very often I need to set item number in itemView of CListView. The $index gives only numbers for current page but not for the whole set of items when pagination is used. It means item index will start from zero on each page.

I have extended CListView a bit like this:




public function renderItems() {

  echo CHtml::openTag($this->itemsTagName,array('class'=>$this->itemsCssClass))."\n";

  $data=$this->dataProvider->getData();

  if(count($data)>0) {

    $owner=$this->getOwner();

    $render=$owner instanceof CController ? 'renderPartial' : 'render';

    foreach($data as $i=>$item) {

      $data=$this->viewData;

      $data['index']=$i;

      $data['data']=$item;

      $data['widget']=$this;

//new part

      if($this->dataProvider->pagination) {

        $data['realIndex']=$i+$this->dataProvider->pagination->currentPage*$this->dataProvider->pagination->pageSize;

      } else {

        $data['realIndex']=$i;

      }

//new part end

      $owner->$render($this->itemView,$data);

    }

  }  else $this->renderEmptyText();

  echo CHtml::closeTag($this->itemsTagName);

}



Now I can have zero-based $realIndex of each item in itemView.

Note that it is necessary to set dataProvider->pagination->validateCurrentPage=false

This is useful for numbering items and setting up unique ids for use in JS and so on…

Comments are highly appreciated!

Do you mean like this?




$widget->dataProvider->getPagination()->currentPage * $widget->dataProvider->getPagination()->pageSize + $index + 1;



Hi,

Yes, if you like it so.

But if you have it in your CListView class you could use it in your code much shorter: $realIndex+1.

And since pagination->params set pagination->validateCurrentPage is not important for the realIndex.

Actually pagination->params always needed to be set even you do not have any. In this case you should set an empty array like this pagination->params=array().

It is important when path format for urls used…

Cheers

Ho can I apply your extension?