【问题标题】:How to passa data from the controller to the database for a list如何将数据从控制器传递到数据库以获取列表
【发布时间】:2014-01-10 19:10:25
【问题描述】:

我用 symfony2 制作了一个网络应用程序,注册用户可以在其中查询文件并将其可视化。我正在尝试将信息从控制器传递到模板。

当我传递单个对象的信息时,它可以正常工作。你可以在这里看到控制器:

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

}

但是,如果我想显示整个列表,我该怎么办? 如果我改变了

       ->find($id);

       ->findAll();

我当然会出错。

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

如何显示整个列表?

感谢您的帮助

【问题讨论】:

  • findAll返回一个数组,你需要写一个循环来处理它们。
  • 我必须把循环放到渲染中,对吧?
  • 可能在渲染周围。也许 Symphony 有一个自动化模式,我不熟悉它。
  • 在 twig 中创建循环,并将列表发送到该 twig 文件 twig.sensiolabs.org/doc/templates.html

标签: php database symfony object doctrine


【解决方案1】:

首先将所有产品数据传递到您的树枝视图

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

然后在您的视图中,您可以将产品及其信息列为

{% 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 %}

编辑

findAll() 将给出所有结果以获取您需要的最新 10 个使用 findBy

findBy(
array(), // $where 
array('id' => 'DESC'), // $orderBy
10, // $limit
0 // $offset
);

【讨论】:

  • 如果我只想显示 10 个结果,我必须更改我的查询表单,不是吗?或者我也可以直接从模板中做吗?例如,显示最近上传的 10 个对象(因此具有更高的 id)。我看到了“->setMaxResults($limit)”,我可以在我的控制器中使用它吗?
猜你喜欢
  • 2018-03-23
  • 2021-02-09
  • 2023-04-05
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 2013-05-09
相关资源
最近更新 更多