N
N
nlan2014-08-01 15:44:26
Yii
nlan, 2014-08-01 15:44:26

How to make CNC pagination in Yii2?

It was possible to make the CNC url through urlManager, but when connecting pagination, the parameters are passed in the form mysite.ru/controllerName?page=2&per-page=2. How to make pagination like mysite.ru/controllerName/page/2 ?
It is also required to change the url of the first page from such mysite.ru/controllerName?page=1&per-page=2 to such mysite.ru/controllerName

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vladimir Kozhin, 2014-08-07
@nlan

to do this, you need to set the rules in the config in the url manager, in the same way as it was done in yii1. more or less like this:

'urlManager': [
  'rules': [
    'controllerName/<page>': 'controllerName/index'
  ]
]

more details here - www.yiiframework.com/doc-2.0/guide-url.html#parame...

I
Igor, 2015-05-05
@mulat

Just figured this out just now. I will give an example code from my project.
Option for yii\widgets\ListView
Controller :

$dataProvider = new ActiveDataProvider([
            'query' => Post::find()->andWhere(['category_id' => $model->id]),
            'pagination' => [
                // Размер выводимых элементов на страницу. 
                // Беру из настроек своего модуля blog
                'pageSize' => Yii::$app->getModule('blog')->postPerPage,
                // Размер эл-тов на страницу по умолчанию. Зачем нужен - поясню после кода
                'defaultPageSize' => Yii::$app->getModule('blog')->postPerPage,
                // Имя параметра, содержащего номер текущей страницы. 
                // (если Ваш отличается от дефолтного 'page')
                'pageParam' => 'pageNum',
                // Так подавляется ссылка на первую страницу вида /category-name-х/1/
                // Вместо неё выведется  /category-name-х/
                'forcePageParam' => false,
            ]
        ]);

The 'defaultPageSize' value should be set to 'pageSize' in order to suppress the Pagination class from adding the 'per-page' parameter to page URLs. But this is necessary for the case when the value of the native 'pageSize' does not suit. I think it's 20.
It is also required to change the url of the first page from such mysite.ru/controllerName?page=1&per-page=2 to such mysite.ru/controllerName
This point is solved by setting the 'forcePageParam' parameter to false.
In order for the route to be picked up from your urlManager, the pattern described in the manager must contain the correct parameter names. Those. in the Pagination class settings - the default value of 'pageParam' is set to 'page'. So pattern for urls should be like this:
//...
// Category with pager
 [
    'pattern' => '<alias:[\w\-]+>/<page:\d+>',
    'route' => 'blog/category/index',
    'suffix' => '/'
  ],
//...

In my case, the pattern for urls is this:
PS
As a result, this option did not suit me myself, because I wanted to leave in the page only links to the pages themselves without links to the Next and Previous post. I did not find how to do it under ListView. And in LinkPager without problems.
Option for yii\widgets\LinkPager
Controller :
$query = Post::find()->andWhere(['category_id' => $model->id]);
        $countQuery = clone $query;
        $pages = new Pagination([
            'totalCount' => $countQuery->count(),
            'pageSize' => Yii::$app->getModule('blog')->postPerPage,
            'defaultPageSize' => Yii::$app->getModule('blog')->postPerPage,
            'pageParam' => 'pageNum',
            'forcePageParam' => false,
        ]);
        $postModels = $query->offset($pages->offset)->limit($pages->limit)->all();

        return $this->render('index', [
            'postModels' => $postModels,
            'pages' => $pages,
        ]);

Performance :
echo LinkPager::widget([
            'pagination' => $pages,
            // Отключаю ссылку "Следующий"
            'nextPageLabel' => false,
            // Отключаю ссылку "Предыдущий"
            'prevPageLabel' => false,
        ]);

It seems to have answered both questions.
PS I'm
using modified LinkPager . In particular, for the sake of setting `activeLinkable` (do not link to the active page), displaying the end page number and displaying insular numbering:
1,2,3,4 ... 44 [45] 46 ... 999

H
Head Hunter, 2016-03-21
@Head-Hunter

<?= ListView::widget([
            'dataProvider' => $dataProvider,
            'itemView' => '_list',
            'layout' => "{items}\n{pager}",
            'summary' => Module::t('view', 'SHOW {count} FROM {totalCount}'),
            'emptyText' => Module::t('view','NO_PUBLISHED_TERMINS_FOUND'),
            'emptyTextOptions' => [
                'tag' => 'p'
            ],
            'itemOptions' => [
                'tag' => 'div',
                'class' => 'news-item',
            ],
            'options' => [
                'tag' => 'div',
                'class' => 'termin-list',
                'id' => 'termin-list',
            ],
            'pager' => [
                'firstPageLabel' => '««',
                'lastPageLabel' => '»»',
                'nextPageLabel' => false,
                'prevPageLabel' => false,
                'maxButtonCount' => 7,
            ],
        ]);?>

Here is an option for ListView to work with LinkPager. - can be useful to someone

I
Igor Vasiliev, 2016-05-19
@Isolution666

А если я хочу сделать ссылку по принципу:

так было: http://домен/ru/site/reviev?page=1&per-page=3
так стало: http://домен/ru/site/reviev/1/3
что мне писать в urlManager ?
правило 'site/reviev/<page:\d+>' => 'site/reviev', работает только для get запросов, что не катит в случае с пагинацией.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question