Pawan Pawan - 7 months ago 222
PHP Question

yii2:Custom Pagination for Gridview in form view

I have included the Gridview widget in

_form.php
file, which is working well. The problem is the filter and pagination.

<?php
$dataProvider = new ActiveDataProvider([
'query' => \app\models\ServiceCharges::find(),
'pagination' => [
'pageSize' => 5,
],
]);

?>
<?php
$searchModel = New \app\models\ServiceChargesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

?>

</div>
</div>
<div>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],

'id',
'service_name',
'room_category',
'charges_cash',
'charges_cashless',

['class' => 'yii\grid\ActionColumn'],
],
]); ?>

</div>


If I am putting the
$dataprovider
pagination part below the
$searchmodel
, pagination works fine, but then filter doesn't work and vice-versa.

How can I have both filter and pagination working in the _form.php.

Any solution will be greatly appreciated.

Thanks

Answer

I have no experience with Yii2 but if it is similar than 1..

Why are you declaring dataProvider twice? I imagine the first one is to be able to customize page size.

So what happens is you use one data provider to set pagination but then you pass a different one to the table.

Second I don't know how your model looks inside but..

Since I can see the search() method returns a dataProvider, you should change the pagination inside there.

Or I think you can change it right after the search() method returns the dataProvider like:

$searchModel = New \app\models\ServiceChargesSearch(); 
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize=5;

So you don't need the first instance of dataProvider that you've declared before.

As for the filters I do not know how it exactly behaves your ServiceChargesSearch::search function

But in Yii1 you normally:

1) Define model 2) Fill it up with data from $_GET 3) Pass $model->search() to grid

If filters still not work you can provide code from the model.