Change Items Per Page In Yii Gridview

Last modified: 
Sunday, March 29th, 2015

Overview

This describes how to change the number of items per page displayed in Yii's CGridview]. This is the display used in the actionAdmin methods created by Gii. This article will briefly touch upon altering the default search query as well.

Do It in The Model

The display of Yii's CGridview can easily be modified in our model's search method. A default search method created by Gii looks something like the code below. This example represents a model with an id, title, and active field.

public function search()
{    
    $criteria=new CDbCriteria;
    
    $criteria->compare('id',$this->id);
    $criteria->compare('name',$this->title,true);
    $criteria->compare('active',$this->active);
    
    return new CActiveDataProvider($this, array('criteria'=>$criteria,
    ));
}

Pagination - Increase Items Per Page

In this example, the default admin action will list all items, 10 items per page, in first-in-first-out sequence. But we want to display 50 items per page instead. To do so, we update the CActiveDataProvider using options available to CPagination :

public function search()
{    
    $criteria=new CDbCriteria;
    
    $criteria->compare('id',$this->id);
    $criteria->compare('name',$this->title,true);
    $criteria->compare('active',$this->active);
    
    return new CActiveDataProvider($this, array('criteria'=>$criteria,
      'pagination' => array(
          'pageSize' => 50,
        ),      
    ));
}

Refining the Criteria to Show Only Active Items and Set the Sort Order

The previous change should now have our admin action generating paginated reports of 50 items per page. Let's refine the CDbCriteria object so that only items where active equal 1 are displayed, and sort the results by highest id to lowest.

public function search()
{    
    $criteria=new CDbCriteria;
    $criteria->condition = 'active = 1';
    $criteria->order = 'id DESC';
    $criteria->compare('id',$this->id);
    $criteria->compare('name',$this->title,true);
    $criteria->compare('active',$this->active);
    
    return new CActiveDataProvider($this, array('criteria'=>$criteria,
      'pagination' => array(
          'pageSize' => 50,
        ),      
    ));
}


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.