via
Db::select("...");
I fetch data from a database.
It is a lot of data. Therefore I would like to display them in a table with several pages. Each page should display 25 records. I wanted to solve this with a pagination, however, this does not work as thought.
<?php foreach($elements->paginate(10) as $element): ?>
This is how I get the first ten elements. How do I get the next ones?
You need a $pagination object and then a navigation that allows you to navigate between the pagination pages, should work similar to how it works with page collections, see
daan
January 31, 2023, 1:34pm
3
While it returns a Collection
iterator by default, $db->query()
fetches data as a Kirby\Toolkit\Obj
which is not a Collection
.
Maybe something like $db->lastResult()->paginate(10)
?
I have already tried this, but it does not work.
I get the following error: Call to undefined method Kirby\Toolkit\Pagination::pageURL()
My code:
controllers/data.php
<?php
return function () {
$elements= Db::select('elements');
return [
'elements' => $elements
];
};
templates/data.php
<?php foreach($list = $elements->paginate(10) as $element): ?>
<p><?= $element->id() ?></p>
<p><?= $element->id() ?></p>
<br>
<?php endforeach ?>
<?php $pagination = $list->pagination() ?>
<nav>
<ul>
<?php if ($pagination->hasPrevPage()): ?>
<li>
<a href="<?= $pagination->prevPageURL() ?>">‹</a>
</li>
<?php else: ?>
<li>
<span>‹</span>
</li>
<?php endif ?>
<?php foreach ($pagination->range(10) as $r): ?>
<li>
<a<?= $pagination->page() === $r ? ' aria-current="page"' : '' ?> href="<?= $pagination->pageURL($r) ?>">
<?= $r ?>
</a>
</li>
<?php endforeach ?>
<?php if ($pagination->hasNextPage()): ?>
<li>
<a href="<?= $pagination->nextPageURL() ?>">›</a>
</li>
<?php else: ?>
<li>
<span>›</span>
</li>
<?php endif ?>
</ul>
</nav>
Yes, the problem is that the pagination object of a toolkit collection doesn’t have a page url… Same as problem described here: Pagination in Kirby 3 problem, Call to undefined method and here: Applying pagination to results from a database - #7 by Milos2504
And since the underlying problem doesn’t seem to be fixed yet…, I guess this needs some workaround.
What does this workaround look like?
I’ve created Db pagination for the virtual users, maybe this is helpful.
<?php
use Kirby\Cms\App;
use Kirby\Database\Db;
use Kirby\Toolkit\Escape;
function pagesPagination(int $total, int $limit): int
{
if ($total === 0) {
return 0;
}
return (int)ceil($total / $limit);
}
function startPagination(?int $page, int $limit): int
{
if($page === null) {
$page = 1;
This file has been truncated. show original
I’m planning to refactor the code above to make a copy of the kirby/Pagination.php at main · getkirby/kirby · GitHub and adapted it to make it work without using collections.
texnixe
February 1, 2023, 12:13pm
8
One workaround for your use case could be to convert your database entries into virtual children.