How do I display pagination in Yii2 GridView?

1.2k views Asked by At

I am getting my dataProvider from which I try to remove some models that don't meet the wanted criteria. This filter is not SQL related and therefore I can't apply it directly to the query. On my view the pagination links are displayed if I leave the dataprovider just as it was. But after I apply the filters to remove the unwanted models, the pagination links disappear. I have tried setting the pagination on my new dataProvider but nothing works.

Here's my code in the controller action:

 $request = Yii::$app->request;
    $search_model = new StaffEmploymentListViewSearch();
    $data_provider = $search_model->search($request->queryParams);

    $models = $data_provider->models;
    for($k=0;$k<count($models);$k++)
    {
        if($models[$k]->employ === null){
            unset($models[$k]);
        }
    }
  
    $config = [
        'pageParam' => 'page',
        'pageSizeParam' => 'per-page',
        'forcePageParam' => true,
        'route' => null,
        'params' => null,
        'urlManager' => null,
        'validatePage' => true,
        'totalCount' => 5214,
        'defaultPageSize' => 20,
        'pageSizeLimit' => [
            '0' => 1,
            '1' => 50
        ],
        'pagesize' => 20
    ];
 
    $data_provider->setModels($models);
    $data_provider->setPagination($config);

    return $this->render('all-staff',[
        'dataProvider' => $data_provider,
        'searchModel' => $search_model
    ]);

Here's my search method:

$query = StaffEmploymentListView::find()
            ->SELECT([
                'PAYROLL_NO', 
                'BIRTH_DATE',
                "ADD_MONTHS(BIRTH_DATE, 70 * 12) AS RETIRE_DATE"
            ]);
    
    // add conditions that should always apply here
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => false,
        'pagination' => [
            'pagesize' => 20,
        ],
    ]);

How do I go about doing this?

1

There are 1 answers

0
Anton Rybalko On BEST ANSWER

Try to use ArrayDataProvider

    $query = StaffEmploymentListView::find()
            ->select([
                'PAYROLL_NO', 
                'BIRTH_DATE',
                "ADD_MONTHS(BIRTH_DATE, 70 * 12) AS RETIRE_DATE"
            ]);
    
    $allModels = [];
    foreach ($query->all as $staffEmployment)
    {
        if ($model->employ === null){
            $allModels[] = $model;
        }
    }

    $dataProvider = new ArrayDataProvider([
        'allModels' => $allModels,
        'pagination' => [
            'pageSize' => 20,
        ],
        'sort' => false
    ]);

    return $this->render('all-staff',[
        'dataProvider' => $data_provider,
        'searchModel' => $search_model // ???
    ]);