【问题标题】:Symfony2: KnpPaginator only show the first page with POST formSymfony2:KnpPaginator 仅显示带有 POST 表单的第一页
【发布时间】:2014-02-03 22:23:42
【问题描述】:

我在一个应用程序中使用这个包。控制器是显示搜索表单、获取响应并对其进行处理的典型控制器(示例):

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(),
            ));
}

当我执行搜索时,我可以正确看到结果列表和分页器。当我按到下一页的链接时出现问题。链接 id 生成良好,URL 以“?p=2”结尾,但似乎没有重新发送表单 POST 数据,因为它将我发送到搜索表单页面($form->isValid() 为 false)。

如果我将表单方法从 POST 更改为 GET 并在 URL 中传递参数:

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

分页器运行完美。

我做错了吗?可以使用 POST 表单吗?

我已经搜索了一个答案,但我看到的所有 KnpPagintor 控制器示例都没有生成带有表单的查询,并且this question 没有帮助我。

谢谢。

【问题讨论】:

  • 您不应该使用 POST 方法来获取过滤后的数据,例如 Google:https://www.google.com/#q=symfony&start=10q 是我搜索的内容,start 是分页器值

标签: symfony post get knppaginator


【解决方案1】:

你不应该使用 POST 方法来获取数据。

否则,如果您需要使用 POST 方法,那么您需要会话中的数据。然而,构建良好的用户体验并不容易,而使用 GET 方法更有意义。

您可以找到extensive documentation about HTTP on MDN

  • 请求数据时应使用 GET 方法。
  • 当您保存数据(例如将评论保存到数据库中)或其他数据操作时,应使用 POST 方法。

Google 在自己的搜索页面上使用 GET

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

q 是我搜索的内容,start 是分页器值。他们可能使用偏移量而不是页码来避免计算偏移量(更快且成本更低)。

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2020-02-22
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多