Mick Segvezent
Mick Segvezent

Reputation: 117

How to set the number of items per page in a CGridView?

I have a project in Yii where there is a CGridView that by default shows 10 records per page. How can I set this to 100 records?

Upvotes: 5

Views: 16075

Answers (3)

shihab mm
shihab mm

Reputation: 525

You can configure the items per page with a dropdown.

enter image description here

To create a section like this. Follow the steps below.

Define custom template for the section "Displaying 1-10 of 128" section on the screenshot.

Add this piece of code with your Gridview properties array.

'summaryText' => 'Displaying {start}-{end} of {count} result(s). ' .
    CHtml::dropDownList('pageSize', $pageSize, Yii::app()->params['pageSizeOptions'], array('class' => 'change-pageSize')) .' rows per page',

Add this line on the top of view

$pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']);

Add Change event in the same view.

jQuery(function ($) {
$('body').on('change','.change-pageSize', function () {
    $.fn.yiiGridView.update('my-grid', {data: {pageSize: $(this).val()}
    })
});
});

Add This line in Model search function, to set the selected rows count in Active data provider.

$pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']);

Then in the controller receive the page size parameter sent from view through ajax. Use the following line of code in controller.

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

Add This configuration in Params.php

'defaultPageSize' => 20,
'pageSizeOptions' => array(-1 =>'All' , 10 => 10, 20 => 20, 50 => 50, 100 => 100, 500 => 500),

This Worked for me!

Upvotes: 0

Hoang-Viet
Hoang-Viet

Reputation: 131

You can configure in Search function of the Model like below:

public function search()
{
    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id,true);
    $criteria->compare('start_year',$this->start_year,true);
    $criteria->compare('end_year',$this->end_year,true);
    $criteria->compare('ref_lang_id',$this->ref_lang_id);
    $criteria->compare('submitted_at',$this->submitted_at,true);
    $criteria->compare('ref_submitted_user_id',$this->ref_submitted_user_id,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'pagination' => array(
            'pageSize' => 30,
        ),
    ));
}

Upvotes: 11

Jon
Jon

Reputation: 437336

Find in your view the place where the CGridView widget is being rendered, and configure the pagination property of the data provider:

$this->widget('zii.widgets.CGridView', array(
    'dataProvider' => array(
         /* other options for the data provider... */
        'pagination' => array('pageSize' => 100),
    ),
    /* other options for the grid view... */
));

Upvotes: 7

Related Questions