简体   繁体   中英

How do I display pagination in Yii2 GridView?

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?

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 // ???
    ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM