Search code examples
phpsymfonypagerfanta

search result combined with pagerfanta


i have an app, which displays a list of items, in the main page i have add form with two inputs, the first will contain the month value and the second one will take a year value; i set up the action inside the controller in that action there is a function that take two arguments "month, year".

/**
 * @Route("/bills",defaults={"page": "1"} , name="bills", methods={"GET"})
 * @Route("/bills/page/{page<[1-9]\d*>}", name="bills_paginated", methods="GET")
 * @param BillRepository $billRepository
 * @param Request $request
 * @param int $page
 * @return Response
 */
public function indexBills(BillRepository $billRepository,Request $request, int $page): Response
{
    $formBills = $this->createForm(BillsType::class);
    $formBills->handleRequest($request);
    $getArgs= $request->query->get('bills');
    $Bills =$billRepository->unpaidBills($getArgs,$page);
    
    return $this->render('homePage/bills.html.twig', [
        'formBills'=>$formBills->createView(),
        'Bills'=> $Bills ,
    ]);
}

when i submit the search form, the result is being displayed as its expected, the page pagination is there too, but when i click the next page for example page '2' and that happens because the $getArgs is empty is there a way to keep the same arguments while changing the page.


Solution

  • When you click on 'Page 2' you don't send 'year' and 'month' data.

    Solution 1 - inject bills form data from controller

    I think, the easiest way is to send the $request->query->get('bills') to the twig as formData for example. And on your twig add the 'bills' : formData in the parameters of your route bills_paginated

    If you do this, symfony will add your form data in your url and you will not lose them when you change your page, so when you do $getArgs= $request->query->get('bills'); you have your data

    Solution 2 - get bills form data from twig

    This is easiest solution, get the bills form data directly in twig like this : {% set formData = app.request.get('bills') %}. And on your twig add the 'bills' : formData in the parameters of your route bills_paginated

    Best solution

    IMO the best and the cleanest solution is to have a route with the year and month inside like this "/bills/year/{year<[1-9]\d*>}/month/{month<[1-9]\d*>}/page/{page<[1-9]\d*>}"