Search code examples
phpyiiyii2yii2-basic-app

Yii2 ValidatePage to give empty output on wrong page number


I am trying to fetch a list of products from a table using my yii2 app and send it accross as a json to lazyload on scroll from the front end. I am using the searchmodel class. Now when data ends, last page data is being send again, i.e., if i have hundred records, the calls for page numbers above 5 would repeatedly send the same data as page number 4. How do i prevent it. PS: Confused about the usage of the validatePage flag reading the documentation.

Here is my code of the controller.

public function actionAjaxIndex()
{

  $searchModel = new productsS();
    $response = (object) ['status' => 0];
  $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $response->status = 1;
        $response->data = array();
        foreach($dataProvider->models as $row){
            foreach($row as $key=>$value){
                $customerDetail[$key] = $value;
            }
            array_push($response->data, $customerDetail);
        }
        return json_encode($response);
}

Can somebody help with the best possible solution to go ahead.


Solution

  • You need to disable $validatePage for your data provider. This setting overwrites page if it is outside of range (so if you have 4 pages of records, but you request 5th page, pagination will automatically switch to 4th page - every page outside of range will display results for last page).

    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->pagination->validatePage = false;