How to add the pagination dropdown list in GridView in Yii2
Home » BLOG » Yii2.0 framework » How to add the pagination dropdown list in GridView in Yii2

How to add the pagination dropdown list in GridView in Yii2

category:  Yii2.0 framework

Earlier, I wrote how to add the summary footer in the gridview widget. The grand total column will sum all the total columns on each page and the default page size of gridview is 20 items per page. I want to be able to change the page size as I want in order to see the new grand total if I choose the search filter. Below is the screenshot that I did.

We will add the extra code in two places which are view and model.

Note that, I generate the CRUD from Gii. So I will show only the code that I add for displaying the pagesize dropdown list only.

Invoice view:

<?= Html::label( Yii::t('frontend', 'Page size: '), 'pagesize', array( 'style' => 'margin-left:10px; margin-top:8px;' ) ) ?>
<?= Html::dropDownList(
    'pagesize', 
    ( isset($_GET['pagesize']) ? $_GET['pagesize'] : 20 ),  // set the default value for the dropdown list
    // set the key and value for the drop down list
    array( 
        20 => 20, 
        50 => 50, 
        100 => 100),
    // add the HTML attritutes for the dropdown list
    // I add pagesize as an id of dropdown list. later on, I will add into the Gridview widget.
    // so when the form is submitted, I can get the $_POST value in InvoiceSearch model.
    array( 
        'id' => 'pagesize', 
        'style' => 'margin-left:5px; margin-top:8px;'
        )
    ) 
?>

The drop-down list above is added before GridView::widget

InvoiceSearch model:

<?php
public function search($params) 
{
    ...
    
    // we must load the params before using it
    $this->load($params);  
    
    // add conditions that should always apply here
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => [
            // this $params['pagesize'] is an id of dropdown list that we set in view file
            'pagesize' => (isset($params['pagesize']) ? $params['pagesize'] :  '20'),
        ],
    ]);    
}
?>

Yep! that’s it. Every time you change the page size in the drop-down list, the page will refresh and shows the new number of items on each page you select.