Бортовой журнал Ктулху

Using pjax in Yii2 for pagination

Pjax is a technology that facilitates updating part of a page without a full reload. In the context of Yii2, Pjax is commonly used to update data on the page, including pagination navigation.

And i give an example how it works.

 

 

Controller

Put your model with all params.

$dataProvider = new ActiveDataProvider([
'query' => $model,
'sort' => false, // вкл\выкл активные заголовки с сортировкой по полю
'pagination' => [
'pageSize' => 50,
],
]);
 
if (\Yii::$app->request->isPjax) {
return $this->renderPartial('index', [
'dataProvider' => $dataProvider
]);
}
 
return $this->render('index',[
'dataProvider' => $dataProvider
]);

View

// add pjax js
$this->registerJs(
"$('body').on('click', '#grid-view-content a[data-pjax=0]', function () {
$.pjax.reload({container: '#pjax-container-id'});
});"
);
 
// add pjax call
Pjax::begin(['id' => 'pjax-container-id']);
echo GridView::widget([
// some code
// add pager with pjax params into gridview
'pager' => [
'class' => LinkPager::class,
'options' => ['class' => 'pagination'],
'prevPageLabel' => '«',
'nextPageLabel' => '»',
'maxButtonCount' => 10,
'prevPageCssClass' => 'prev',
'nextPageCssClass' => 'next',
'firstPageCssClass' => 'first',
'lastPageCssClass' => 'last',
'linkOptions' => ['data-pjax' => true],
'pagination' => $dataProvider->getPagination(),
],
]);
Pjax::end();
 
// fix pagination to show pjax params
$js = <<< JS
$(document).on('click', '#pjax-container-id .pagination a', function(e){
e.preventDefault();
var url = $(this).attr('href');
 
 
$.pjax({
url: url,
container: '#pjax-container-id',
timeout: 30000,
}).done(function() {
// 
 });
});
JS;

$this->registerJs($js);

And we have got working pjax pagination.