2014-01-10 53 views
0

我使用symfony2製作了一個Web應用程序,其中註冊用戶可以查詢文件並將其可視化。我試圖將信息從控制器傳遞給模板。如何將數據從控制器傳遞到數據庫以獲得列表

當我傳遞單個對象的信息時,它正常工作。你可以在這裏看到控制器:

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). 

如何顯示整個列表?

謝謝您的幫助

+0

'findAll'返回一個數組,你需要寫一個循環來處理它們。 – Barmar

+0

我必須將循環放入渲染中,對嗎? –

+0

可能圍繞渲染。也許Symphony有一個自動化模式,我不熟悉它。 – Barmar

回答

0

首先所有的產品數據傳遞到您的樹枝視圖

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 
); 
+0

如果我只想顯示10個結果,我必須更改我的查詢表單,不是它?或者我也可以直接從模板中進行操作?例如,顯示上傳的最後10個對象(所以使用更高的ID)。 我看到「 - > setMaxResults($ limit)」,我可以在我的控制器中使用它嗎? –

+0

@GianniAlessandro看到我更新的答案 –

相關問題