I have a page that displays 6 items (institutions in my case) on each paginated section of the page (therefore each page). I display the items in a random order using shuffle.
I use Symfony 4 and Pagerfanta for the pagination. The problem I face is that every time I go to the next page, my query is being shuffled again. Randomizing the order is not the problem, the problem is this happens every time the user goes to the next page. It should only happen on the first page and remain in that order. I have read a similar question here, but the problem is that all solutions seem to imply a completely new paginator. Is there a method to use both pagerfanta and solve my problem?
My code right now:
InstitutionController.php
// I query for the list of items (institutions)
$q = $request->query->get('q');
$query = $institutionRepository->searchAndSortPublished($q);
// I randomize the order of institutions
shuffle($query);
$pagerfanta = $paginationHelper->paginate($request, $query, 6);
return $this->render('institution/index.html.twig', [ 'paginator' => $pagerfanta, 'institutions' => $query, 'q' => $q]);
PaginationHelper.php
//...
public function paginate($request, $array, $maxPerPage = 10)
{
$page = $request->query->get('page', 1);
$adapter = new ArrayAdapter($array);
$pagerfanta = new Pagerfanta($adapter);
$pagerfanta->setMaxPerPage($maxPerPage);
$pagerfanta->setCurrentPage($page);
return $pagerfanta;
}
If you are randomising the result, then the only real way would be to do your DB call on the first time, then store the rows (or just ids) in a session var or some other storage. Then you can refer to that result each time. Might also actually speed your page up!
Note that even if you had a seeded shuffle, you'd still need to fetch every record first.