Published on

How to setup drop down for page size in CGridView in Yii Framework

Authors
  • avatar
    Name
    Bal Singh
    Twitter

I needed to create drop down for page size in CGridView. So I decided to share this code with all of you.  Here is the view of drop down in CGridView.

So to create drop down as shown above, Below is the code inserted in admin.php where CGridView is used.
code in view/category/admin.php

<?php  
$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']);  
  
 $this->widget('bootstrap.widgets.TbGridView',
    array(  
        'id'=>'category-grid',  
        'dataProvider'=>$model->search(),  
        'filter'=>$model,  
        'summaryText'=>'Displaying {start}-{end} of {count} result(s). ' .
            CHtml::dropDownList( 
                'pageSize',  
                $pageSize,
                Yii::app()->params['pageSizeOptions'], 
                array('class'=>'change-pageSize')) . ' rows per page',  
        'columns'=>array(  
            'id',  
            .......    
        ),  
    )
);  
  
<script type="text/javascript">  
jQuery(function($) {  
$('.change-pageSize').live('change', function() {  
        $.fn.yiiGridView.update('category-grid',{ data:{ pageSize: $(this).val() }})  
    });  
</script> 

and in controllers under actionAdmin(), i added this code on top of action

if (isset($_GET['pageSize'])) {  
    Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);  
}  

and in the model (e.g. model/Category) the data provider in search() i added

$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']);  
               
return new CActiveDataProvider($this, 
    array(  
    'criteria'=>$criteria,  
        'sort'=>$sort,  
        'pagination' => array('pageSize' => $pageSize),  
    )
);  

And finally don't forgot to set default params value in config/main.php as

'params'=>array(  
    .......
   'defaultPageSize'=>20,  
   'pageSizeOptions'=>array(10=>10,20=>20,50=>50,100=>100)         
),  

By adding this code you can setup dynamic pagination for CGridView as shown below.