I found myself in the need for a dropDownList to select the page size on a CGridView. I was amazed that only a few lines of code where required. So i thought i’d share.
On top of my controller action for the gridview (if you used CRUD, this is actionAdmin() ) i added:
// page size drop down changed
if (isset($_GET['pageSize'])) {
Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
unset($_GET['pageSize']); // would interfere with pager and repetitive page size change
}
In the model (e.g. model/User.php) the data provider in search() is configured like:
return new CActiveDataProvider(get_class($this),array(
'pagination'=>array(
'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']),
),
'criteria'=>$criteria,
));
And finally the view (e.g. views/user/admin.php) :
<?php
// put this somewhere on top
$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']); ?>
<?php
// we use header of button column for the drop down
// so change the CButtonColumn in columns array like this:
...
array(
'class'=>'CButtonColumn',
'header'=>CHtml::dropDownList('pageSize',$pageSize,array(20=>20,50=>50,100=>100),array(
// change 'user-grid' to the actual id of your grid!!
'onchange'=>"$.fn.yiiGridView.update('user-grid',{ data:{pageSize: $(this).val() }})",
)),
),
Et voilà, we have a page size selector that keeps it’s value in user state.
EDIT:
Forgot to mention the configuration in the application parameters:
// Accessable with Yii::app()->params['paramName']
'params'=>array (
'defaultPageSize'=>20,
EDIT2:
Changed to match the CRUD generated code.