### Install KnpPaginatorBundle via Composer Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Use Composer to add the bundle to your Symfony project. This is the standard installation method. ```bash composer require knplabs/knp-paginator-bundle ``` -------------------------------- ### Configure KnpPaginatorBundle in YAML Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Configure default query parameter names, templates, and other options for the KnpPaginatorBundle using a YAML configuration file. This example shows how to set exception handling, page range, and default options for sorting and filtering. ```yaml knp_paginator: convert_exception: false # throw a 404 exception when an invalid page is requested page_range: 5 # number of links shown in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links to page 4, 5, 6) remove_first_page_param: false # remove the page query parameter from the first page link default_options: page_name: page # page query parameter name sort_field_name: sort # sort field query parameter name sort_direction_name: direction # sort direction query parameter name distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements filter_field_name: filterField # filter field query parameter name filter_value_name: filterValue # filter value query parameter name page_out_of_range: ignore # ignore, fix, or throwException when the page is out of range default_limit: 10 # default number of items per page template: pagination: '@KnpPaginator/Pagination/sliding.html.twig' # sliding pagination controls template rel_links: '@KnpPaginator/Pagination/rel_links.html.twig' # tags template sortable: '@KnpPaginator/Pagination/sortable_link.html.twig' # sort link template filtration: '@KnpPaginator/Pagination/filtration.html.twig' # filters template ``` -------------------------------- ### Override Default Translations Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Customize pagination translations by creating translation files in the `project_root/translations/` directory. The file name format should be `domain.locale.format`, for example, `KnpPaginatorBundle.tr.yaml`. ```yaml label_previous: "Önceki" label_next: "Sonraki" filter_searchword: "Arama kelimesi" ``` -------------------------------- ### Configure Global Pagination Templates Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Set default templates for pagination and sorting in the bundle configuration file. ```yaml knp_paginator.template.pagination: my_pagination.html.twig ``` ```yaml knp_paginator.template.sortable: my_sortable.html.twig ``` -------------------------------- ### Clone the repository Source: https://github.com/knplabs/knppaginatorbundle/blob/master/CONTRIBUTING.md Use this command to create a local copy of the forked repository. ```bash git clone git@github.com:USERNAME/KnpPaginatorBundle.git ``` -------------------------------- ### Configure Pagination Routes and Parameters Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Define specific routes and query parameters for generated pagination URLs. ```php get('knp_paginator'); $pagination = $paginator->paginate($target, $page); $pagination->setUsedRoute('blog_articles'); ``` ```php setParam('category', 'news'); ``` -------------------------------- ### Configure KnpPaginatorBundle in PHP Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Use this configuration file to define default pagination behavior, query parameter names, and template paths for the bundle. ```php // config/packages/paginator.php extension('knp_paginator', [ 'convert_exception' => false, // throw a 404 exception when an invalid page is requested 'page_range' => 5, // number of links shown in the pagination menu (e.g: you have 10 pages, a page_range of 3, on the 5th page you'll see links 'remove_first_page_param' => false, // remove the page query parameter from the first page link 'default_options' => [ 'page_name' => 'page', // page query parameter name 'sort_field_name' => 'sort', // sort field query parameter name 'sort_direction_name' => 'direction', // sort direction query parameter name 'distinct' => true, // ensure distinct results, useful when ORM queries are using GROUP BY statements 'filter_field_name' => 'filterField', // filter field query parameter name 'filter_value_name' => 'filterValue', // filter value query parameter name 'page_out_of_range' => 'ignore', // ignore, fix, or throwException when the page is out of range 'default_limit' => 10 // default number of items per page ], 'template' => [ 'pagination' => '@KnpPaginator/Pagination/sliding.html.twig', // sliding pagination controls template 'rel_links' => '@KnpPaginator/Pagination/rel_links.html.twig', // tags template 'sortable' => '@KnpPaginator/Pagination/sortable_link.html.twig', // sort link template 'filtration' => '@KnpPaginator/Pagination/filtration.html.twig' // filters template ] ]); }; ``` -------------------------------- ### Configure KnpPaginatorBundle Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Customize default pagination options, templates, and behavior settings in the configuration file. This allows for fine-tuning the pagination experience. ```yaml # config/packages/knp_paginator.yaml knp_paginator: page_range: 5 # number of links shown in pagination menu page_limit: 100 # maximum number of pages (null for unlimited) convert_exception: false # throw 404 on invalid page request remove_first_page_param: false # remove page param from first page link default_options: page_name: page # page query parameter name sort_field_name: sort # sort field query parameter name sort_direction_name: direction # sort direction query parameter name distinct: true # ensure distinct results filter_field_name: filterField # filter field query parameter name filter_value_name: filterValue # filter value query parameter name page_out_of_range: ignore # options: 'ignore', 'fix', 'throwException' default_limit: 10 # default items per page template: pagination: '@KnpPaginator/Pagination/bootstrap_v5_pagination.html.twig' rel_links: '@KnpPaginator/Pagination/rel_links.html.twig' sortable: '@KnpPaginator/Pagination/bootstrap_v5_fa_sortable_link.html.twig' filtration: '@KnpPaginator/Pagination/bootstrap_v5_filtration.html.twig' ``` -------------------------------- ### Run tests Source: https://github.com/knplabs/knppaginatorbundle/blob/master/CONTRIBUTING.md Execute the project test suite to ensure changes do not introduce regressions. ```bash composer test ``` -------------------------------- ### Custom Pagination Subscriber for Filesystem in PHP Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Implement EventSubscriberInterface to listen for 'knp_pager.items' and handle custom data sources like filesystem directories. This allows paginating any data type. ```php target) || !is_dir($event->target)) { return; } $finder = new Finder(); $finder->files() ->depth('< 4') ->in($event->target) ->sortByName(); $files = iterator_to_array($finder->getIterator()); $event->count = count($files); $event->items = array_slice($files, $event->getOffset(), $event->getLimit()); $event->stopPropagation(); } public static function getSubscribedEvents(): array { return [ 'knp_pager.items' => ['items', 1] // Higher priority to override defaults ]; } } ``` ```yaml # config/services.yaml services: App\Subscriber\PaginateDirectorySubscriber: tags: ['kernel.event_subscriber'] ``` ```php paginate( '/var/www/uploads', // Directory path as target $request->query->getInt('page', 1), 20 ); return $this->render('browser/index.html.twig', [ 'pagination' => $pagination, ]); } ``` -------------------------------- ### Setting Route and Parameters for Pagination URLs Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Configures the route and additional parameters for generating pagination URLs, useful in sub-requests or when extra parameters are needed. Requires injecting PaginatorInterface, a repository, and Request object. ```php paginate( $productRepo->findByCategorySlug($slug), $request->query->getInt('page', 1), 12 ); // Set explicit route for pagination URLs $pagination->setUsedRoute('category_show'); // Add route parameters needed for URL generation $pagination->setParam('slug', $slug); return $this->render('category/show.html.twig', [ 'slug' => $slug, 'pagination' => $pagination, ]); } } ``` -------------------------------- ### PHP: Controller Action for Directory Pagination Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/custom_pagination_subscribers.md This controller action utilizes the KnpPaginator service to paginate the contents of a directory. It takes the KnpPaginatorInterface and the Request object as arguments. The pagination is initiated by calling the paginate method with the directory path, current page number, and items per page. ```php paginate(__DIR__.'/../', $request->query->getInt('page', 1), 10); return $this->render('demo/test.html.twig', ['pagination' => $pagination]); } ``` -------------------------------- ### Accessing Pagination Data in a Controller Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Demonstrates how to paginate query results and access various pagination metadata like total items, current page, and sort order. Requires injecting PaginatorInterface, a repository, and Request object. ```php paginate( $repo->createQueryBuilder('p'), $request->query->getInt('page', 1), 10 ); // Access pagination data $paginationData = $pagination->getPaginationData(); // Returns: [ // 'last' => 10, // 'current' => 1, // 'numItemsPerPage' => 10, // 'first' => 1, // 'pageCount' => 10, // 'totalCount' => 100, // 'pageRange' => 5, // 'startPage' => 1, // 'endPage' => 5, // 'previous' => null, // 'next' => 2, // 'pagesInRange' => [1, 2, 3, 4, 5], // 'firstPageInRange' => 1, // 'lastPageInRange' => 5, // 'currentItemCount' => 10, // 'firstItemNumber' => 1, // 'lastItemNumber' => 10, // ] // Other useful methods $totalItems = $pagination->getTotalItemCount(); $currentPage = $pagination->getPage(); $pageCount = $pagination->getPageCount(); $isSortedByName = $pagination->isSorted('p.name'); $sortField = $pagination->getSort(); $sortDirection = $pagination->getDirection(); $route = $pagination->getRoute(); $params = $pagination->getParams(); return $this->json([ 'data' => iterator_to_array($pagination->getIterator()), 'meta' => [ 'total' => $totalItems, 'page' => $currentPage, 'pages' => $pageCount, 'per_page' => $pagination->getItemNumberPerPage(), ], ]); } } ``` -------------------------------- ### Customize Bulma Rendering Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Configure Bulma pagination styles including alignment, size, and rounded buttons. ```php $pagination->setCustomParameters([ 'align' => 'center', 'size' => 'large', 'rounded' => true, ]); ``` ```twig {{ knp_pagination_render(pagination, null, {}, { 'align': 'center', 'size': 'large', 'rounded': true, }) }} ``` -------------------------------- ### PHP: Custom Directory Pagination Subscriber Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/custom_pagination_subscribers.md This subscriber listens to the 'knp_pager.items' event to paginate files within a specified directory. It uses Symfony's Finder component to locate files up to a certain depth and then slices the results based on pagination parameters. Ensure the target is a string and a valid directory before proceeding. ```php target) || !is_dir($event->target)) { return; } $finder = new Finder(); $finder ->files() ->depth('< 4') // 3 levels ->in($event->target) ; $iterator = $finder->getIterator(); $files = iterator_to_array($iterator); $event->count = count($files); $event->items = array_slice($files, $event->getOffset(), $event->getLimit()); $event->stopPropagation(); } public static function getSubscribedEvents(): array { return [ 'knp_pager.items' => ['items', 1/* increased priority to override any internal */] ]; } } ``` -------------------------------- ### Create a new branch Source: https://github.com/knplabs/knppaginatorbundle/blob/master/CONTRIBUTING.md Create and switch to a new feature or fix branch based on the master branch. ```bash git checkout -b BRANCH_NAME master ``` -------------------------------- ### Manual Count for Complex Queries in PHP Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Use the 'knp_paginator.count' hint to provide a manual count for queries with composite keys or complex JOINs. This is essential when automatic counting is not feasible. ```php createQuery('SELECT COUNT(r) FROM App\Entity\Report r WHERE r.status = :status') ->setParameter('status', 'active') ->getSingleScalarResult(); // Main query with manual count hint $query = $em->createQuery('SELECT r FROM App\Entity\Report r WHERE r.status = :status ORDER BY r.createdAt DESC') ->setParameter('status', 'active') ->setHint('knp_paginator.count', $count); $pagination = $paginator->paginate( $query, $request->query->getInt('page', 1), 10, ['distinct' => false] // Disable distinct for manual counting ); return $this->render('report/list.html.twig', [ 'pagination' => $pagination, ]); } } ``` -------------------------------- ### Configure Pagination Translations Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Define custom labels for pagination controls in YAML translation files. ```yaml # translations/KnpPaginatorBundle.en.yaml label_previous: "Previous" label_next: "Next" filter_searchword: "Search" ``` ```yaml # translations/KnpPaginatorBundle.fr.yaml label_previous: "Precedent" label_next: "Suivant" filter_searchword: "Recherche" ``` -------------------------------- ### Render Pagination and Sortable Headers in Twig Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Use knp_pagination_render for navigation links and knp_pagination_sortable for column headers. The knp_pagination_rel_links function is used within the head block for SEO. ```twig {# templates/article/list.html.twig #} {% extends 'base.html.twig' %} {% block title %}Articles{% endblock %} {% block head %} {{ parent() }} {# Add rel links for SEO (prev/next) #} {{ knp_pagination_rel_links(pagination) }} {% endblock %} {% block body %}

Articles

Total: {{ pagination.getTotalItemCount }} articles

{# Sortable column headers #} {% for article in pagination %} {% else %} {% endfor %}
{{ knp_pagination_sortable(pagination, 'ID', 'a.id') }} {{ knp_pagination_sortable(pagination, 'Title', 'a.title') }} {{ knp_pagination_sortable(pagination, 'Created', 'a.createdAt') }} Actions
{{ article.id }} {{ article.title }} {{ article.createdAt|date('Y-m-d H:i') }} View
No articles found.
{# Render pagination navigation #}
{{ knp_pagination_render(pagination) }}
{% endblock %} ``` -------------------------------- ### Custom Translation File for KnpPaginatorBundle Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md If your locale is not available, create a custom translation file to define labels like 'Next' and 'Previous'. Substitute 'en' with your specific language code. ```yaml label_next: Next label_previous: Previous ``` -------------------------------- ### Configure multiple paginators in a controller Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Customize parameter names in the options array to prevent conflicts when using multiple paginators on one page. ```php paginate( $articleRepo->createQueryBuilder('a')->orderBy('a.createdAt', 'DESC'), $request->query->getInt('article_page', 1), 5, [ 'pageParameterName' => 'article_page', 'sortFieldParameterName' => 'article_sort', 'sortDirectionParameterName' => 'article_dir', ] ); // Second paginator for comments $comments = $paginator->paginate( $commentRepo->createQueryBuilder('c')->orderBy('c.createdAt', 'DESC'), $request->query->getInt('comment_page', 1), 10, [ 'pageParameterName' => 'comment_page', 'sortFieldParameterName' => 'comment_sort', 'sortDirectionParameterName' => 'comment_dir', ] ); return $this->render('dashboard/index.html.twig', [ 'articles' => $articles, 'comments' => $comments, ]); } } ``` -------------------------------- ### Add KnpPaginatorBundle to Application Kernel Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Manually enable the KnpPaginatorBundle in your application's kernel if you are not using Symfony Flex. Ensure this is done within the registerBundles method. ```php // app/AppKernel.php public function registerBundles() { return [ // ... new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(), // ... ]; } ``` -------------------------------- ### Adjust Pagination Range and Limits Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Control the number of pages displayed or the total page limit. ```php setPageRange(7); ``` ```twig {% do pagination.setPageRange(7) %} ``` ```php setPageLimit(25); ``` ```twig {% do pagination.setPageLimit(25) %} ``` -------------------------------- ### Set Custom Templates and Options in Controller Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Programmatically set custom templates for pagination, sorting, and filtering. You can also configure the page range, page limit, and custom parameters for the template. ```php paginate( $productRepo->findAllQuery(), $request->query->getInt('page', 1), 12 ); // Set templates programmatically $pagination->setTemplate('@KnpPaginator/Pagination/tailwindcss_pagination.html.twig'); $pagination->setSortableTemplate('@KnpPaginator/Pagination/sortable_link.html.twig'); $pagination->setFiltrationTemplate('@KnpPaginator/Pagination/filtration.html.twig'); // Set page range (number of page links to show) $pagination->setPageRange(7); // Set page limit (max pages) $pagination->setPageLimit(50); // Set custom parameters for template $pagination->setCustomParameters([ 'align' => 'center', 'size' => 'large', 'rounded' => true, ]); return $this->render('product/list.html.twig', [ 'pagination' => $pagination, ]); } } ``` -------------------------------- ### XML Configuration for PaginatorAware Service Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md This XML configuration defines a service tagged with 'knp_paginator.injectable', allowing it to be aware of the Knp Paginator. Ensure this is part of your Symfony service configuration. ```xml MyBundle\Repository\PaginatorAwareRepository ``` -------------------------------- ### Twig: Displaying Paginated Directory Contents Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/custom_pagination_subscribers.md This Twig template extends a base layout and displays the paginated directory contents in an HTML table. It iterates through the 'pagination' object provided by the controller, displaying the base name and path of each file. The 'knp_pagination_render' function is used to display the pagination navigation controls. ```html {% extends "layout.html.twig" %} {% block title "My demo" %} {% block content %}

Demo

{# sorting of properties based on query components #} {# table body #} {% for file in pagination %} {% endfor %}
base name path
{{ file.baseName }} {{ file.path }}
{# display navigation #} {% endblock %} ``` -------------------------------- ### Render Pagination in Twig Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Use the render helper to display pagination with custom templates. ```twig {{ knp_pagination_render(pagination, 'my_pagination.html.twig') }} ``` ```twig {{ knp_pagination_sortable(pagination, 'date', 'c.publishedAt', {}, {}, 'KnpPaginator/Pagination/bootstrap_v4_sortable_link.html.twig') }} {{ knp_pagination_render(pagination, 'KnpPaginator/Pagination/bootstrap_v4_pagination.html.twig') }} ``` -------------------------------- ### Configure Sortable Columns with Custom Options Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Implement conditional styling using isSorted, sort by multiple fields, and define fixed sort directions or custom CSS classes for headers. ```twig {# templates/product/list.html.twig #} {# Basic sortable column #} {# Check if column is currently sorted for conditional styling #} {{ knp_pagination_sortable(pagination, 'Price', 'p.price') }} {# Sort by multiple fields #} {{ knp_pagination_sortable(pagination, 'Category', ['p.category', 'p.subcategory']) }} {# Fixed direction sort links #} {# With custom CSS class #} {% for product in pagination %} {% endfor %}
{{ knp_pagination_sortable(pagination, 'Name', 'p.name') }} {{ knp_pagination_sortable(pagination, 'Rating (Low to High)', 'p.rating', {}, {'direction': 'asc'}) }} | {{ knp_pagination_sortable(pagination, 'Rating (High to Low)', 'p.rating', {}, {'direction': 'desc'}) }} {{ knp_pagination_sortable(pagination, 'Date', 'p.createdAt', {'class': 'custom-sort-link'}) }}
{{ product.name }} {{ product.price|number_format(2) }} {{ product.category }} {{ product.rating }} {{ product.createdAt|date('M d, Y') }}
{{ knp_pagination_render(pagination) }} ``` -------------------------------- ### Display Pagination Controls and Sortable Headers in Twig Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Render pagination navigation, total item count, and sortable table headers within your Twig templates. Use `knp_pagination_render` for navigation and `knp_pagination_sortable` for column headers. ```twig {# total items count #}
{{ pagination.getTotalItemCount }}
{# sorting of properties based on query components #} {{ knp_pagination_sortable(pagination, 'Title', 'a.title') }} {{ knp_pagination_sortable(pagination, 'Release', ['a.date', 'a.time']) }} {# table body #} {% for article in pagination %} {% endfor %}
{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}
{{ article.id }} {{ article.title }} {{ article.date | date('Y-m-d') }}, {{ article.time | date('H:i:s') }}
{# display navigation #} ``` -------------------------------- ### Render Pagination in Twig Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Pass custom query and view parameters to the pagination template. ```jinja {{ knp_pagination_render( pagination, '@KnpPaginator/Pagination/twitter_bootstrap_v4_pagination.html.twig', { 'queryParam1': 'param1 value', 'queryParam2': 'param2 value' }, { 'viewParam1': 'param1 value', 'viewParam2': 'param2 value' }, ) }} ``` -------------------------------- ### Register KnpPaginatorBundle in Symfony Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Register the bundle in your Symfony application's configuration file if you are not using Symfony Flex. This ensures the bundle's services are available. ```php // config/bundles.php (if not using Symfony Flex) return [ // ... Knp\Bundle\PaginatorBundle\KnpPaginatorBundle::class => ['all' => true], ]; ``` -------------------------------- ### Set Custom Template Parameters Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Pass custom variables to pagination templates or extend existing ones. ```php setCustomParameters([ 'align' => 'center', # center|right (for template: twitter_bootstrap_v4_pagination and foundation_v6_pagination) 'size' => 'large', # small|large (for template: twitter_bootstrap_v4_pagination) 'style' => 'bottom', 'span_class' => 'whatever', ]); ``` ```yaml knp_paginator: template: pagination: 'pagination.html.twig' ``` ```twig {% set align = 'left' %} {% set size = 'large' %} {% set style = 'bottom' %} {% extends '@KnpPaginator/Pagination/twitter_bootstrap_v5_pagination.html.twig' %} ``` -------------------------------- ### Manually set count for pagination Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/manual_counting.md Use this approach when dealing with composite identifiers or multiple FROM components. Ensure the count query returns a single scalar result. ```php createQuery('SELECT COUNT(c) FROM Entity\CompositeKey c') ->getSingleScalarResult() ; $query = $entityManager ->createQuery('SELECT c FROM Entity\CompositeKey c') ->setHint('knp_paginator.count', $count) ; $pagination = $paginator->paginate($query, 1, 10, ['distinct' => false]); ``` -------------------------------- ### Default Paginator Configuration Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/paginator_configuration.md Configure default options for the KnpPaginatorBundle. This includes setting the page range, limit, query parameter names, and template paths. Ensure this configuration is placed in your Symfony application's configuration file. ```yaml knp_paginator: page_range: 5 # default page range used in pagination control page_limit: 100 # page limit for pagination control; to disable set this field to ~ (null) convert_exception: false # convert paginator exception (e.g. non-positive page and/or limit) into 404 error default_options: page_name: page # page query parameter name sort_field_name: sort # sort field query parameter name; to disable sorting set this field to ~ (null) sort_direction_name: direction # sort direction query parameter name distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements page_out_of_range: ignore # if page number exceeds the last page. Options: 'fix'(return last page); 'throwException' default_limit: 10 # default number of items per page template: pagination: @KnpPaginator/Pagination/sliding.html.twig # sliding pagination controls template rel_links: @KnpPaginator/Pagination/rel_links.html.twig # tags template sortable: @KnpPaginator/Pagination/sortable_link.html.twig # sort link template ``` -------------------------------- ### Enable Translator in Framework Configuration Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Ensure the Symfony translator is configured to recognize the translation directory. ```yaml # config/packages/framework.yaml framework: translator: fallbacks: ['en'] default_path: '%kernel.project_dir%/translations' ``` -------------------------------- ### XML: Registering the Event Subscriber Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/custom_pagination_subscribers.md Register the custom subscriber as a service in your Symfony application's service configuration file (e.g., config/services.xml). This ensures that the event dispatcher recognizes and utilizes your subscriber. ```xml ``` -------------------------------- ### Add filter form and sortable headers in Twig Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Use knp_pagination_filter to generate search inputs and knp_pagination_sortable for column sorting headers. ```twig {# templates/user/list.html.twig #} {# Add filter form above the table #} {{ knp_pagination_filter(pagination, { 'u.username': 'Username', 'u.email': 'Email', 'u.fullName': 'Full Name' }) }} {% for user in pagination %} {% endfor %}
{{ knp_pagination_sortable(pagination, 'Username', 'u.username') }} {{ knp_pagination_sortable(pagination, 'Email', 'u.email') }} {{ knp_pagination_sortable(pagination, 'Full Name', 'u.fullName') }}
{{ user.username }} {{ user.email }} {{ user.fullName }}
{{ knp_pagination_render(pagination) }} ``` -------------------------------- ### Display Rel Links for Pagination Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Include rel="next" and rel="prev" links in the head of your HTML for SEO and navigation purposes. This function requires the pagination object. ```twig {# rel links for pagination #} {{ knp_pagination_rel_links(pagination) }} ``` -------------------------------- ### Paginate Doctrine ORM Queries in Controller Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Use the PaginatorInterface service in your controller to paginate Doctrine ORM queries. Inject the service and call the paginate method with your query, current page, and limit. ```php getRepository(Article::class) ->createQueryBuilder('a') ->where('a.published = :published') ->setParameter('published', true) ->orderBy('a.createdAt', 'DESC'); $pagination = $paginator->paginate( $queryBuilder, // query to paginate $request->query->getInt('page', 1), // current page number 10 // items per page ); return $this->render('article/list.html.twig', [ 'pagination' => $pagination, ]); } } ``` -------------------------------- ### Filter Query Results Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Add filtering capabilities to the pagination output. ```html {{ knp_pagination_filter(pagination, { 'entity.name': 'Name', }) }} ``` -------------------------------- ### Override Template in Twig Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Render pagination using a specified template and pass custom query and view parameters. Also demonstrates how to render sortable links with custom templates. ```twig {# Override template in Twig #} {{ knp_pagination_render( pagination, '@KnpPaginator/Pagination/bootstrap_v5_pagination.html.twig', {'category': 'electronics'}, {# query params #} {'align': 'center', 'size': 'small'} {# view params #} ) }} {{ knp_pagination_sortable( pagination, 'Title', 'p.title', {}, {# options #} {}, {# params #} 'my_custom_sortable.html.twig' {# custom template #} ) }} ``` -------------------------------- ### Override Templates Directly Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Apply custom templates to specific pagination instances via PHP or Twig. ```php $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate($target, $page); $pagination->setTemplate('my_pagination.html.twig'); $pagination->setRelLinksTemplate('my_rel_links.html.twig'); $pagination->setSortableTemplate('my_sortable.html.twig'); ``` ```html {% do pagination.setTemplate('my_pagination.html.twig') %} ``` -------------------------------- ### Customize Paginator Query Parameters Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Override default query parameter names for pagination and sorting in the controller. ```php get('knp_paginator'); $pagination = $paginator->paginate( $query, // target to paginate $this->get('request')->query->getInt('section', 1), // page parameter, now section 10, // limit per page ['pageParameterName' => 'section', 'sortDirectionParameterName' => 'dir'] ); ``` -------------------------------- ### Paginate an Array of Data in Controller Source: https://context7.com/knplabs/knppaginatorbundle/llms.txt Paginate plain PHP arrays directly. This is useful for data sourced from APIs, files, or any iterable source. ```php 'document.pdf', 'size' => 1024, 'type' => 'pdf'], ['name' => 'image.jpg', 'size' => 2048, 'type' => 'image'], ['name' => 'video.mp4', 'size' => 10240, 'type' => 'video'], // ... more items ]; $pagination = $paginator->paginate( $files, $request->query->getInt('page', 1), 10 ); return $this->render('file/list.html.twig', [ 'pagination' => $pagination, ]); } } ``` -------------------------------- ### Enable Translator in Symfony Configuration Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md To ensure proper functioning, activate the translator component in your Symfony configuration. This is often required for internationalization features within bundles. ```yaml framework: translator: { fallbacks: ['%locale%'] } ``` -------------------------------- ### Define Sorting Direction Source: https://github.com/knplabs/knppaginatorbundle/blob/master/docs/templates.md Force specific sorting directions in the sortable links. ```html {{ knp_pagination_sortable(pagination, 'Title A-Z', 'a.title', {}, {'direction': 'asc'}) }} {{ knp_pagination_sortable(pagination, 'Title Z-A', 'a.title', {}, {'direction': 'desc'}) }} ``` -------------------------------- ### Paginate Doctrine Query in Controller Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Use the paginator service to paginate a Doctrine Query object in a controller. Ensure you pass the query object itself, not the result, along with the current page number and limit per page. ```php // App\Controller\ArticleController.php public function listAction(EntityManagerInterface $em, PaginatorInterface $paginator, Request $request) { $dql = "SELECT a FROM AcmeMainBundle:Article a"; $query = $em->createQuery($dql); $pagination = $paginator->paginate( $query, /* query NOT result */ $request->query->getInt('page', 1), /* page number */ 10 /* limit per page */ ); // parameters to template return $this->render('article/list.html.twig', ['pagination' => $pagination]); } ``` -------------------------------- ### Configure Default Locale for Translations Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Set the default locale for Symfony to automatically pick up translations. This is configured within the `framework` section of your `config.yaml`. ```yaml framework: default_locale: tr ``` -------------------------------- ### Translate Sortable Column Headers Source: https://github.com/knplabs/knppaginatorbundle/blob/master/README.md Translate column headers used with `knp_pagination_sortable` by applying the `trans` filter. This allows for dynamic translation of column titles based on locale. ```twig {# sorting of properties based on query components #} {{ knp_pagination_sortable(pagination, 'Title', 'a.title')|raw }}
{{ knp_pagination_sortable(pagination, 'Id'|trans({foo:'bar'},'messages'), 'a.id' )|raw }} {{ knp_pagination_sortable(pagination, 'Author'|trans({}, 'messages'), 'a.author' )|raw }}
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.