dpuwov1487 2015-07-28 01:38
浏览 43

如何使用symfony2对搜索结果进行分页?

I am working on a project using symfony2. I already have my search function and it is already working. But what I want is to have pagination on the search results since there are times that there are a lots of data being retrieve. How can I possibly do it?

Here is my code :

public function searchAction (Request $request) {

        $request = $this->getRequest();
        $data = $request->get('search');

        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery (
            'SELECT a,b,c FROM SampleBundle:transactDetail a
            JOIN a.transact b
            JOIN b.transactType c
            WHERE b.pNumber LIKE :data
            OR b.senderId LIKE :data'
        )
        ->setParameter('data', "%$data%");
        $result = $query->getResult();

        if ($result == null ) {
            return $this->render('SampleBundle:Sample:noresult.html.twig');
        }
        return $this->render('SampleBundle:Sample:search.html.twig', array('result' => $result));
    }

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dtmm0148603 2015-07-28 10:36
    关注

    This is an example of your code with Paginator :

    public function searchAction(Request $request, $firstResult = 0, $maxResults = 100)
    {
        $request = $this->getRequest();
        $data = $request->get('search');
    
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            'SELECT a,b,c FROM SampleBundle:transactDetail a
                JOIN a.transact b
                JOIN b.transactType c
                WHERE b.pNumber LIKE :data
                OR b.senderId LIKE :data'
        )
            ->setParameter('data', "%$data%")
            ->setFirstResult($firstResult)
            ->setMaxResults($maxResults);
    
        $result = new Paginator($query);
    
        if ($result == null) {
            return $this->render('SampleBundle:Sample:noresult.html.twig');
        }
    
        return $this->render('SampleBundle:Sample:search.html.twig', array('result' => $result));
    }
    

    And if you would like to count the total just count($result);.
    Paginator has Countable et IteratorAggregate interfaces.
    So you can loop on your result without problem.

    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加