Add simple pagination to Symfony projects
comoser require osw3/symfony-pagination
In your composer.json file, change the line of the dependency to prepare futures updates of the bundle.
"osw3/symfony-pagination": "*",
Add the bundle in the config/bundle.php
file.
return [
OSW3\Pagination\PaginationBundle::class => ['all' => true],
];
#[Route('/', name: 'app_book_index', methods: ['GET'])]
public function index(BookRepository $bookRepository, PaginationService $paginationService): Response
{
/// 1. Set up the Paging
/// --
// A. Set the repository to the service
$repository = $paginationService->setRepository($bookRepository);
// B. (optional) Set the repository method
$repository->setMethod('findBy');
/// 2. Find entities
/// --
// A. Find entities with optional sorter
$books = $repository->find(['title' => 'ASC']);
// B. or Find entities based on criteria and optional sorter
// $books = $repository->findBy(
// ['author' => "John"],
// ['title' => 'ASC']
// );
/// 3. Render the view
/// --
// Render the view with books list and the pagination service
return $this->render('book/index.html.twig', [
'paginationService' => $paginationService,
'books' => $books,
]);
}
{{ pagination({
paginationService: paginationService,
route: 'app_book_index',
absolute: true
}) }}
{{ pagination_total() }}
{{ pagination_pages() }}
{{ pagination_page() }}
{{ pagination_per_page() }}