Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Knp Paginator Bundle Laravel Package

knplabs/knp-paginator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require knplabs/knp-paginator-bundle
    

    Ensure KnpPaginatorBundle is enabled in config/bundles.php (auto-enabled in Symfony Flex).

  2. Basic Pagination in Controller

    use Knp\Component\Pager\PaginatorInterface;
    
    public function index(PaginatorInterface $paginator, EntityManagerInterface $em)
    {
        $products = $em->getRepository(Product::class)->findAll();
        $pagination = $paginator->paginate(
            $products,
            $request->query->getInt('page', 1), // Page number
            10 // Items per page
        );
        return $this->render('product/index.html.twig', ['pagination' => $pagination]);
    }
    
  3. First Use Case: Twig Rendering Use the default Twig template:

    {{ knp_pagination_render(pagination) }}
    

    Or customize with:

    {% for product in pagination %}
        {{ product.name }}
    {% endfor %}
    

Implementation Patterns

Core Workflows

  1. Query-Based Pagination (ORM/Doctrine)

    $query = $em->getRepository(Product::class)->createQueryBuilder('p')
        ->where('p.price > :min')
        ->setParameter('min', $request->query->get('min_price'))
        ->getQuery();
    $pagination = $paginator->paginate(
        $query,
        $request->query->getInt('page', 1),
        12,
        ['filter' => 'price_asc'] // Route parameters
    );
    
  2. Collection Pagination (Non-Query Data)

    $collection = $service->getFilteredProducts();
    $pagination = $paginator->paginate(
        $collection,
        $request->query->getInt('page', 1),
        10
    );
    
  3. Dynamic Sorting

    $sortField = $request->query->get('sort', 'name');
    $sortDir = $request->query->get('dir', 'ASC');
    $queryBuilder = $em->getRepository(Product::class)->createQueryBuilder('p')
        ->orderBy("p.$sortField", $sortDir);
    
  4. Integration with Forms

    {{ form_start(form) }}
        {{ form_widget(form) }}
        {{ knp_pagination_render(pagination) }}
    {{ form_end(form) }}
    

Advanced Patterns

  • Custom Templates: Override Twig templates in templates/KnpPaginator/ or use {% extends 'KnpPaginator:SlidingPaginationSliding.html.twig' %}.
  • Event Subscribers: Extend functionality via Knp\Paginator\Event\PaginationEvent.
  • API Pagination: Return metadata in JSON:
    return $this->json([
        'data' => $pagination,
        'meta' => [
            'total' => $pagination->getTotalItemCount(),
            'pages' => $pagination->getPageCount(),
        ]
    ]);
    

Gotchas and Tips

Pitfalls

  1. Query vs. Collection:

    • Query objects (Doctrine) require paginate() with a Query instance.
    • Collections/Arrays must be passed directly (no Query wrapper).
    • Error: InvalidArgumentException if mixing types.
  2. Route Parameters:

    • Ensure route and routeParameters in paginate() match your route (e.g., ['filter' => $request->query->all()]).
    • Fix: Use useQueryString: true to preserve existing query params:
      $paginator->paginate($query, $page, 10, [], ['useQueryString' => true]);
      
  3. Twig Template Overrides:

    • Clear cache after creating custom templates (php bin/console cache:clear).
    • Debug: Check var/cache/dev/ for compiled templates if styles break.
  4. Performance:

    • Avoid paginating unbounded queries (e.g., findAll()). Use COUNT() or getResult() with DISTINCT for large datasets.
    • Tip: Use setMaxResults() and setFirstResult() manually for complex queries.

Debugging Tips

  • Log Queries: Enable Doctrine logging to verify SQL:
    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  • Check Pagination Object:
    dump($pagination->getCurrentPageNumber(), $pagination->getItemCountOnPage());
    
  • Event Debugging: Listen to Knp\Paginator\Event\PaginationEvent to inspect pre/post-pagination data.

Extension Points

  1. Custom Adapters:

  2. Template Variables:

    • Access all Twig vars via pagination object:
      {{ pagination.hasPreviousPage() ? link_to_route('product_index', 'Previous') : '' }}
      
  3. Configuration:

    • Override defaults in config/packages/knp_paginator.yaml:
      knp_paginator:
          page_range: 5       # Number of page links shown
          default_range: 10   # Items per page
          template:
              pagination: 'custom_template.html.twig'
      
  4. Symfony UX Integration:

    • Combine with Symfony UX for reactive pagination:
      <div data-controller="pagination" data-pagination-url="{{ path('product_index') }}">
          {{ knp_pagination_render(pagination) }}
      </div>
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware