Shahid Thaika
Shahid Thaika

Reputation: 2305

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'] ]);

Upvotes: 8

Views: 22400

Answers (4)

KevDev
KevDev

Reputation: 59

Following Yii's getting started tutorial, $dataProvider has a setPagination method.

...
/** Basic generated code from Gii **/
$searchModel = new AlbumSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

/** Paginate & Show 5 items in the table */
$dataProvider->setPagination(['pageSize' => 5]); 
...

The top answer is excessive because it creates a new ActiveDataProvider(...) and re-inserts its own query just to set the pagination. Please be guided.

Upvotes: 2

enter image description here

$dataProvider->pagination = ['pageSize' => 10];

Upvotes: -1

Alexei
Alexei

Reputation: 71

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

Upvotes: 6

GAMITG
GAMITG

Reputation: 3818

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 ],
        ]);

Upvotes: 15

Related Questions