Open a specific page of grid by the id of the record in yii1

168 views Asked by At

I work with yii1.

I have a multi-page list of records, which is displayed using CGridView, sorted in a certain way.

I have id of the record. And I want to open the page on which this record with this exact id is displayed.

Roughly speaking, link /list?too=123 opens the 12th page of the grid, and among all records on this page there is an entry with id 123.

What's the easiest way to do this?

2

There are 2 answers

0
Hmmm On

My way of doing it-

  • Write code to get page number from the item id. In this case controller action will calculate which page needs to be loaded, using the existing/seperate search.
  • Pass this page number in the view file, where the grid is getting loaded.
  • If this special page number is passed, then just load that page when passing $model->search() to the CGridView.

Hope it helps.

0
Alex On

You can extend CGridView and write your own method to search page.

MyGridView.php

<?php
Yii::import('zii.widgets.grid.CGridView');
class MyGridView extends CGridView {

public function init()
{
    if (!isset($_GET[$this->dataProvider->getPagination()->pageVar]) && isset($_GET['too']))
        $this->searchPage();
    parent::init();
}

public function searchPage(){
    $baseCriteria=$this->dataProvider->getCriteria();
    $criteria=clone $this->dataProvider->getCriteria();

    if(($sort=$this->dataProvider->getSort())!==false)
    {
        // set model criteria so that CSort can use its table alias setting
        if($baseCriteria!==null)
        {
            $c=clone $baseCriteria;
            $c->mergeWith($criteria);
            $this->dataProvider->model->setDbCriteria($c);
        }
        else
            $this->dataProvider->model->setDbCriteria($criteria);
        $sort->applyOrder($criteria);
    }

    $this->dataProvider->model->setDbCriteria($baseCriteria!==null ? clone $baseCriteria : null);
    $data=$this->dataProvider->model->findAll($criteria);

    $position = 0;
    foreach($data as $model) {
        $position++;
        if ($model->uid == $_GET['too']) {
            $curPage = ceil($position /  $this->dataProvider->getPagination()->pageSize);
            $_GET[$this->dataProvider->getPagination()->pageVar] = $curPage;
        }
    }
}}