Pagination in Yii 2
Pagination in Yii 2

Pagination

When there are too much data to be displayed on a single page, a common strategy is to display them in multiple pages and on each page only display a small portion of the data. This strategy is known as pagination.

Yii uses a [[yii\data\Pagination]] object to represent the information about a pagination scheme. In particular,

  • [[yii\data\Pagination::$totalCount|total count]] specifies the total number of data items. Note that this is usually much more than the number of data items needed to display on a single page.
  • [[yii\data\Pagination::$pageSize|page size]] specifies how many data items each page contains. The default value is 20.
  • [[yii\data\Pagination::$page|current page]] gives the current page number (zero-based). The default value is 0, meaning the first page.

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



With a fully specified [[yii\data\Pagination]] object, you can retrieve and display data partially. For example, if you are fetching data from a database, you can specify the OFFSET and LIMIT clause of the DB query with the corresponding values provided by the pagination. Below is an example,

use yii\data\Pagination;

// build a DB query to get all articles with status = 1
$query = Article::find()->where(['status' => 1]);

// get the total number of articles (but do not fetch the article data yet)
$count = $query->count();

// create a pagination object with the total count
$pagination = new Pagination(['totalCount' => $count]);

// limit the query using the pagination and retrieve the articles
$articles = $query->offset($pagination->offset)
    ->limit($pagination->limit)
    ->all();

Which page of articles will be returned in the above example? It depends on whether a query parameter named page is given. By default, the pagination will attempt to set the [[yii\data\Pagination::$page|current page]] to be the value of the page parameter. If the parameter is not provided, then it will default to 0.

To facilitate building the UI element that supports pagination, Yii provides the [[yii\widgets\LinkPager]] widget that displays a list of page buttons upon which users can click to indicate which page of data should be displayed. The widget takes a pagination object so that it knows what is the current page and how many page buttons should be displayed. For example,

use yii\widgets\LinkPager;

echo LinkPager::widget([
    'pagination' => $pagination,
]);

If you want to build UI element manually, you may use [[yii\data\Pagination::createUrl()]] to create URLs that would lead to different pages. The method requires a page parameter and will create a properly formatted URL containing the page parameter. For example,

// specifies the route that the URL to be created should use
// If you do not specify this, the currently requested route will be used
$pagination->route = 'article/index';

// displays: /index.php?r=article%2Findex&page=100
echo $pagination->createUrl(100);

// displays: /index.php?r=article%2Findex&page=101
echo $pagination->createUrl(101);

Tip: You can customize the name of the page query parameter by configuring the [[yii\data\Pagination::pageParam|pageParam]] property when creating the pagination object.

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu