Search code examples
symfonytwigpagerfanta

Using only Pagerfanta helpers with Symfony 2 and Twig


I have an application that consumes a webservice. My app send request to webservice like this:

Request example:

https://mywebservice.com/interesting-route/?page=4&limit=30

So I receive just a slice of result, not the complete array, else I could use ArrayAdapter to paginate in my controller. I wanna use just the twig extension to generate DOM elements in my views.

Response example:

{
  results:
    [
      {
        title: 'Nice title',
        body: 'Nice body'
      },
      ...,
      {
        title: 'Nice title',
        body: 'Nice body'
      },
    ],
  total: 1350,
  limit: 30
]

What's the way, maybe using FixedAdapter?

Thanks


Solution

  • As you say, the FixedAdapter should do what you need here. Here's some sample controller code you could adapt:

    public function someAction(Request $request)
    {
        $page = 1;
        if ($request->get('page') !== null) {
            $page = $request->get('page');
        }
        $totalResults = // call your webservice to get a total
        $limit = 30;
    
        $slice = $this->callMyWebserviceInterestingRoute($page, $limit);
    
        $adapter = new FixedAdapter($totalResults, $slice);
        $pagerfanta = new Pagerfanta($adapter);
        $pagerfanta->setMaxPerPage($limit);
        $pagerfanta->setCurrentPage($page);
    
        return $this->render('default/pages.html.twig', [
            'my_pager' => $pagerfanta,
        ]);
    }
    

    Hope this helps.