Question

I'm using this bundle in an application. The controller is the typical that shows a search form, take the response and process it (an example):

public function indexAction()
{
    $request = $this->getRequest();

    $example = new Example();

    $form = $this->createForm(new ExampleFindType(), $example, array(
            'action' => $this->generateUrl('example_find'),
            'method' => 'POST',
    ));

    $form->handleRequest($request);

    if ($form->isValid())
    {
        $em = $this->getDoctrine()->getManager();

        $examples = $em->getRepository('ApplicationExampleBundle:Example')
            ->find_by_fields($example);

        $paginator  = $this->get('knp_paginator');              

        $pagination = $paginator->paginate(
                $examples,
                $this->get('request')->query->get('p', 1),
                20
        );

        return $this->render('ApplicationExampleBundle:Default:searchResults.html.twig',
                array('pagination' => $pagination));
    }

    return $this->render('ApplicationExampleBundle:Default:index.html.twig',
            array('form' => $form->createView(),
            ));
}

When I perform the search I see the results list and the paginator correctly. The problem appears when I press the link to the next page. The link id generated well, with the URL ending with "?p=2" but it seems that the form POST data is not resent because it sent me to the search form page ($form->isValid() is false).

If I change the form method from POST to GET and pass the parameters in the URL:

$form = $this->createForm(new ExampleFindType(), $example, array(
           'action' => $this->generateUrl('example_find'),
           'method' => 'GET',
));

the paginator works perfect.

Am I doing something wrong? Is possible to use a POST form?

I've searched an answer but all the KnpPagintor controller examples I've seen don't generate the query with forms, and this question hasn't helped me.

Thanks.

Was it helpful?

Solution

You shouldn't use POST method to get data.

Otherwise, if you need to use the POST method then you need the data in the session. However it's difficult to build a nice user experience while it just makes more sense to use a GET method.

You can find an extensive documentation about HTTP on MDN.

  • A GET method should be used when you request data.
  • A POST method should be used when you save data (like saving a comment into a database) or other data manipulation.

Google uses a GET on their own search page.

https://www.google.com/#q=symfony&start=10

q is what I searched for and start is the paginator value. They probably use an offset instead of a page number to avoid calculating the offset (faster and less expensive).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top