D
D
Dmitry Dobryshin2020-11-02 12:17:35
Yii
Dmitry Dobryshin, 2020-11-02 12:17:35

How to find the page number in the paginator in Yii2 DataProvider by ID?

From the list of records page, I go either to editing or adding a new record. After saving, you need to go to the page where there is a previously edited or added new entry. Naturally, the entry id is passed to actionIndex, but the first page of the list is always shown.
How to find out the page number on which the post with the given id is located?

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save())
        {
            return $this->redirect([ 'index', 'id' => $model->id ]);
        }

        $searchModelM = new MovingSearch([ 'item_id' => $model->id ]);
        $dataProviderM = $searchModelM->search(Yii::$app->request->queryParams);

         return $this->render('update', [
            'searchModelM'  => $searchModelM,
            'dataProviderM' => $dataProviderM,
            'model'         => $model,
        ]);
    }

    public function actionIndex()
    {
        $searchModel = new ItemsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


Clarification. It is necessary to display exactly all records, and not only with a specific id, otherwise I could use the filter ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Dobryshin, 2020-11-02
@DimkaI

In general, it turned out not a very optimal solution, but it works:

public function actionIndex()
    {
        $searchModel = new ItemsSearch();
        if (isset(Yii::$app->request->queryParams['id'])) {
            $id = Yii::$app->request->queryParams['id'];
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            $dataProvider->query->select(Items::tableName() . '.id');
            $pageSize = $dataProvider->pagination->pageSize;
            $dataProvider->pagination = FALSE;
            $rows = $dataProvider->getModels();
            $page = 0;
            foreach ($rows as $key => $val) {
                if ($id == $val->id) {
                    $page = ceil(($key + 1) / $pageSize);
                    break;
                }
            }
            return $this->redirect(['index', 'page' => $page]);
        }
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

Maybe someone will need it in the future.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question