Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FantomX1-github/f49998ab961d842b139b7ca1de52b31a to your computer and use it in GitHub Desktop.
Save FantomX1-github/f49998ab961d842b139b7ca1de52b31a to your computer and use it in GitHub Desktop.
Yii: drop down to choose page size for CGridView
// 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