donglie1994 2014-01-10 19:10
浏览 29
已采纳

如何将数据从控制器传递到数据库以获取列表

I made a web-application with symfony2, where a registrated user can query for a file and visualize it. I'm trying to pass the information from the controller to the template.

When I pass the information of a single object, it works properly. You can see the controller here:

 public function showAction($id)
 {
       $product = $this->getDoctrine()
       ->getRepository('AcmeBundle:Product')
       ->find($id);

       if (!$product) {
       throw $this->createNotFoundException(
           'Nessun prodotto trovato per l\'id '.$id
       );
       }       

       return $this->render('AcmeGroundStationBundle::showdata.html.twig', array('Id'    => $product->getId(), 'Name' => $product->getName(), 'UploadTime'=> $product-  >getUploadTime()));

}

But what can I do if I want to display the whole list? If I change the

       ->find($id);

with

       ->findAll();

of course I get error.

( Call to a member function getId() on a non-object).

How can I display the whole list?

Thank you for your help

  • 写回答

1条回答 默认 最新

  • dongzai3139 2014-01-10 19:46
    关注

    First pass all the products data to your twig view

    public function showAction()
    {
    $products = $this->getDoctrine()
    ->getRepository('AcmeBundle:Product')
    ->findAll();
    
    if (empty($products)) {
    throw $this->createNotFoundException(
        'No products found'
    );
    }
    
    return $this->render('AcmeGroundStationBundle::showdata.html.twig', 
    array('products' => $products)); 
    }
    

    Then in your view you can list products with their information as

    {% if products is defined and products is not empty %}
    
        {% for p in products %}
    
           id : {{  p.getId() }} <br>
           Name: {{  p.getName() }} <br>
           Upload Time: {{  p.getUploadTime() }} <br>
    
        {% endfor %}
    
    {% endif %}
    

    EDIT

    findAll() will give all the results to get the latest 10 you need use findBy

    findBy(
    array(), // $where 
    array('id' => 'DESC'), // $orderBy
    10, // $limit
    0 // $offset
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀