Forked from umidjons/drop-down-page-size-cgrid-view.php
Created
December 28, 2017 15:58
-
-
Save FantomX1-github/f49998ab961d842b139b7ca1de52b31a to your computer and use it in GitHub Desktop.
Yii: drop down to choose page size for CGridView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in config/main.php | |
'params' => array( | |
'defaultPageSize' => 20, | |
), | |
// in controller action | |
public function actionIndex() | |
{ | |
if ( isset( $_GET[ 'pageSize' ] ) ) | |
{ | |
Yii::app()->user->setState( 'pageSize', (int) $_GET[ 'pageSize' ] ); | |
unset( $_GET[ 'pageSize' ] ); | |
} | |
$model = new MyModel( 'search' ); | |
$model->unsetAttributes(); | |
if ( isset( $_GET[ 'MyModel' ] ) ) | |
$model->attributes = $_GET[ 'MyModel' ]; | |
$this->render( 'index', array( 'model' => $model ) ); | |
} | |
// in model | |
public function search() | |
{ | |
$criteria = new CDbCriteria; | |
$criteria->compare( 'product_code', $this->product_code ); | |
$criteria->compare( 'product_name', $this->product_name, true ); | |
$criteria->compare( 'product_price', $this->product_price, true ); | |
$criteria->compare( 'request_time', $this->request_time, true ); | |
$criteria->order = 'request_time DESC, product_code'; | |
return new CActiveDataProvider( $this, array( | |
'criteria' => $criteria, | |
'pagination' => array( | |
'pageSize' => Yii::app()->user->getState( 'pageSize', Yii::app()->params[ 'defaultPageSize' ] ), | |
), | |
) ); | |
} | |
// in index.php view | |
<p> | |
<?php | |
$pageSize = Yii::app()->user->getState( 'pageSize', Yii::app()->params[ 'defaultPageSize' ] ); | |
$pageSizeDropDown = CHtml::dropDownList( | |
'pageSize', | |
$pageSize, | |
array( 10 => 10, 25 => 25, 50 => 50, 100 => 100 ), | |
array( | |
'class' => 'change-pagesize', | |
'onchange' => "$.fn.yiiGridView.update('grid-view-id',{data:{pageSize:$(this).val()}});", | |
) | |
); | |
?> | |
<div class="page-size-wrap"> | |
<span>Display by:</span><?= $pageSizeDropDown; ?> | |
</div> | |
<?php Yii::app()->clientScript->registerCss( 'initPageSizeCSS', '.page-size-wrap{text-align: right;}' ); ?> | |
<?php | |
$this->widget( 'zii.widgets.grid.CGridView', array( | |
'id' => 'grid-view-id', | |
'dataProvider' => $model->search(), | |
'filter' => $model, | |
'summaryText' => '{start} - {end} / {count}', | |
'columns' => array( | |
array( 'name' => 'product_code' ), | |
array( 'name' => 'product_name' ), | |
array( 'name' => 'product_price' ), | |
array( 'name' => 'request_time', 'filter' => false ), | |
), | |
) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment