Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paging and Filter in Yii2 Gridview

I used the CRUD generator in Yii2 and it generated the following code for my actionIndex controller...

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

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

I am trying to do two things to this default code:

1) Set the page size so that the gridview displaying it only shows 10 rows

2) Modify the $searchModel such that it only returns records where the status column in the table matches certain multiple values (IN Operator)... or better yet, all records that don't match a given value.

For #1, I see many examples to set the 'pagination' while using ActiveDataProvider, but none for search(). This code didn't work for me...

$dataProvider = $searchModel->search(
    Yii::$app->request->queryParams, ['pagination' => [ 'pageSize' => 10 ]]
);

For #2, I know we can filter by declaring the new LeadSearch object as...

$searchModel = new LeadSearch([ 'status' => 'open' ]);

...but something like this doesn't work...

$searchModel = new LeadSearch([ 'status' => ['open', 'pending'] ]);
like image 252
Shahid Thaika Avatar asked Sep 09 '15 14:09

Shahid Thaika


1 Answers

You need to add pagination option in ActiveDataProvider in search model and also put where or andWhere at $query condition.

$query = modalName::find()->andWhere([ 'status' => ['open', 'pending'] ]);

$dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [ 'pageSize' => 10 ],
        ]);
like image 114
2 revs Avatar answered Oct 25 '22 12:10

2 revs