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

Pagerfanta Bundle Laravel Package

white-october/pagerfanta-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require white-october/pagerfanta-bundle
    

    For Symfony 3.4/4.4/5.x, use the fork: composer require babdev/pagerfanta-bundle.

  2. Enable the Bundle: Add to config/bundles.php:

    WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle::class => ['all' => true],
    

    (Replace with BabDev\PagerfantaBundle\BabDevPagerfantaBundle for the fork.)

  3. First Use Case: Create a Pagerfanta instance in a controller and render it in Twig:

    // src/Controller/ExampleController.php
    use Pagerfanta\Pagerfanta;
    use Pagerfanta\Adapter\ArrayAdapter;
    
    public function indexAction()
    {
        $adapter = new ArrayAdapter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        $pagerfanta = new Pagerfanta($adapter);
        $pagerfanta->setMaxPerPage(3);
    
        return $this->render('example/index.html.twig', [
            'pagerfanta' => $pagerfanta,
        ]);
    }
    
  4. Render in Twig:

    {% render_pagerfanta pagerfanta %}
    

    This uses the default view. Customize later via configuration.


Implementation Patterns

Core Workflow

  1. Adapter Integration: Use Pagerfanta with any adapter (e.g., DoctrineORMAdapter for Doctrine entities):

    use Pagerfanta\Adapter\DoctrineORMAdapter;
    
    $adapter = new DoctrineORMAdapter(
        $entityRepository->createQueryBuilder('e')->getQuery()
    );
    $pagerfanta = new Pagerfanta($adapter);
    
  2. Twig Rendering:

    • Default View: {% render_pagerfanta pagerfanta %}
    • Custom View: {% render_pagerfanta pagerfanta with {'view': 'custom_view'} %}
    • Options: {% render_pagerfanta pagerfanta with {'view': 'default', 'options': {'max_per_page': 5}} %}
  3. Configuration: Override defaults in config/packages/white_october_pagerfanta.yaml (or bab_dev_pagerfanta.yaml for the fork):

    white_october_pagerfanta:
        views:
            default:
                template: '@WhiteOctoberPagerfanta/default.html.twig'
                options:
                    max_per_page: 10
                    default_outside_page_range: 2
    
  4. Pagination in Forms: Pass pagerfanta to Twig and use it in form actions:

    <a href="{{ path('example_index', {'page': pagerfanta.getCurrentPage() + 1}) }}">
        Next
    </a>
    

Advanced Patterns

  1. Dynamic Views: Create reusable view configurations in Twig:

    {% render_pagerfanta pagerfanta with {'view': 'bootstrap'} %}
    

    Define bootstrap in config or use a service.

  2. Service Integration: Inject PagerfantaView service for dynamic rendering:

    use WhiteOctober\PagerfantaBundle\Twig\PagerfantaExtension;
    
    public function __construct(PagerfantaExtension $pagerfantaExtension) {
        $this->pagerfantaExtension = $pagerfantaExtension;
    }
    
    public function renderPagerfanta($pagerfanta, $view = 'default', $options = []) {
        return $this->pagerfantaExtension->render($pagerfanta, $view, $options);
    }
    
  3. API Responses: Serialize pagination metadata for APIs:

    return $this->json([
        'data' => $pagerfanta->getCurrentPageResults(),
        'pagination' => [
            'total_items' => $pagerfanta->getNbResults(),
            'total_pages' => $pagerfanta->getNbPages(),
            'current_page' => $pagerfanta->getCurrentPage(),
        ],
    ]);
    
  4. Event Listeners: Hook into PagerfantaEvents (e.g., View.Pagerfanta.Views.Load) to modify views dynamically.


Gotchas and Tips

Common Pitfalls

  1. Deprecation Warnings:

    • The original bundle is archived. Use the BabDev fork for Symfony 3.4+/4.x/5.x.
    • Symfony 2.0.x users must use the symfony2.0 branch.
  2. Twig Template Paths:

    • Ensure Twig templates (e.g., default.html.twig) exist in @WhiteOctoberPagerfanta/ or override them in your bundle.
    • Default path: vendor/white-october/pagerfanta-bundle/Resources/views/.
  3. Adapter Quirks:

    • DoctrineORMAdapter: Ensure your QueryBuilder is properly configured to return results for pagination.
    • ArrayAdapter: Use only for small datasets; large arrays may cause memory issues.
  4. Configuration Overrides:

    • YAML config keys are case-sensitive (max_per_page vs. MaxPerPage).
    • Overrides in config/packages/ take precedence over bundle defaults.
  5. Caching Issues:

    • Pagerfanta caches page results by default. Clear cache if pagination behaves unexpectedly:
      php bin/console cache:clear
      

Debugging Tips

  1. Check Pagerfanta State: Dump the object to verify configuration:

    dump($pagerfanta->getCurrentPage(), $pagerfanta->getNbPages());
    
  2. Twig Debugging:

    • Use {% debug pagerfanta %} to inspect the object in Twig.
    • Verify the render_pagerfanta function is available:
      {% if pagerfanta is defined and pagerfanta|length > 0 %}
          {% render_pagerfanta pagerfanta %}
      {% endif %}
      
  3. View Loading Errors:

    • If Twig throws TemplateNotFoundException, ensure:
      • The template exists in the correct path.
      • The view name in config matches the template filename (e.g., defaultdefault.html.twig).
  4. Performance:

    • Avoid loading all results into memory. Use setMaxPerPage() and lazy-loading adapters.
    • For large datasets, consider server-side pagination (e.g., DoctrineORMAdapter with setUseOutputWalkers).

Extension Points

  1. Custom Views: Extend the default view by creating a new template and configuring it:

    # config/packages/white_october_pagerfanta.yaml
    white_october_pagerfanta:
        views:
            custom:
                template: '@YourBundle/Pagerfanta/custom.html.twig'
                options:
                    previous_label: '« Previous'
                    next_label: 'Next »'
    
  2. Dynamic Options: Pass options dynamically in Twig:

    {% set options = {
        'max_per_page': 5,
        'default_outside_page_range': 3,
        'view_parameters': {'class': 'pagination'}
    } %}
    {% render_pagerfanta pagerfanta with {'options': options} %}
    
  3. Event Subscribers: Listen to PagerfantaEvents to modify behavior:

    use Pagerfanta\Event\View\ViewEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CustomPagerfantaSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'view.pagerfanta.views.load' => 'onViewLoad',
            ];
        }
    
        public function onViewLoad(ViewEvent $event)
        {
            $view = $event->getView();
            $view->template = '@YourBundle/Pagerfanta/custom.html.twig';
        }
    }
    
  4. Integration with Forms: Use Pagerfanta with Symfony Forms for paginated CRUD:

    $form = $this->createForm(YourType::class, $pagerfanta->getCurrentPageResults());
    $form->handleRequest($request);
    
  5. Localization: Override labels in config:

    white_october_pagerfanta:
        views:
            default:
                options:
                    previous_label: 'Anterior'
                    next_label: 'Siguiente'
                    first_label: 'Primero'
                    last_label: 'Último'
    
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