Home » BLOG » Yii2.0 framework » Multiple grids on one page in Yii2

Multiple grids on one page in Yii2

category:  Yii2.0 framework

Recently I upgrade my Yii2 application. What I do, I add two Gridview widgets on one page. One Gridview shows the pagination under the data table which is a default from Gridview. Another Gridview shows the pagination, column sortable and filters on each column. These three functions also are the default functionalities from Gridview.

After the changes, everything seems working fine until I notice the pagination of two Gridview widgets won’t work properly.

Pagination issue

Every time I click on the pagination of one of the Gridview widgets, the other Gridview pagination is changed too. That means I click on page 2 on one Gridview, both Gridview paginations change to page 2 which is not correct. It should be only one Gridview which I click on page 2, will change to page 2.

Solution

To fix the pagination issue, you will go to your search model. In my case, my search modal is TransactionSearch.

In my TransactionSearch model, I add pageParam and sortParam attributes in ActiveDataProvider() as below.

public function search($params)
    {
        // model query
        $query = Transaction::find()->where(['user_id' => Yii::$app->user->id])->orderBy('trans_date DESC, id DESC');

        // load $_POST(but Yii2 uses $params) that is submitted from the search Form from the Gridview widget
        $this->load($params);
        

        $pages = 20;
        // add conditions that should always apply here
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => (isset($params['pagesize']) ? $params['pagesize'] : $pages),
                'pageParam' => 'trans-current-page',
            ],
            'sort' => [
                'sortParam' => 'trans-sort'
            ]
        ]);
...

The idea is, we will give a unique name for the pagination param and sort param for both Gridviews. This way, Gridview won’t be conflict and work independently on the same page.

What I do, for the pagination, I set the pageParam and give a unique name for my Gridviews. I have two Gridviews on one page so I give the unique name for both Gridviews. The example above, I shows only one Gridview.

For the column sort, I set the sortParam and give a unique name for my Gridviews. Same as the pageParame setting, I give the unique name of sortParam for both Gridview.

And that’s it. You can add multiple Gridview widget on one page as you like but you just need to give the unique name for the pageParam and sortParam.

  •  
  •  
  •  
  •  
  •