2013-10-04 12 views
-2

我想添加for循环为php中的变量填充数据。因此,我得到的行查询 result.how应用循环,并获得查询结果在dql中的行数?如何设置循环查询结果,然后传递给树枝文件?

这里是我的代码:

public function invoicepreviewAction(){ 
    if(isset($_SESSION['invoiceid'])) { 
     $invoiceid=$_SESSION['invoiceid']; 
    } 
    if(isset($_SESSION['date'])) { 
     $dateofinvoice=$_SESSION['date']; 
    } 
    $em = $this->getDoctrine()->getManager(); 
    $query = $em->createQuery("select a.companyName,a.companyAddress,a.companyPobox,a.companyCity,a.companyCountry,c.firstName,c.lastName,c.address,c.city,c.country,c.phoneNumber,i.notes from InvoicesInvoicesBundle:Invoices i,ClientsClientsBundle:Clients c,AccountsAccountsBundle:Accounts a where i.id='".$invoiceid."' and i.accountID=a.id and i.clientID=c.id"); 
    $invoices = $query->getResult(); 
    $companyname=$invoices[0]['companyName']; 
    $comanyaddress=$invoices[0]['companyAddress']; 
    $companypobox=$invoices[0]['companyPobox']; 
    $companycity=$invoices[0]['companyCity']; 
    $companycountry=$invoices[0]['companyCountry']; 
    $firstname=$invoices[0]['firstName']; 
    $lastname=$invoices[0]['lastName']; 
    $address=$invoices[0]['address']; 
    $city=$invoices[0]['city']; 
    $country=$invoices[0]['country']; 
    $notes=$invoices[0]['notes']; 
    $phonenumber=$invoices[0]['phoneNumber']; 
    $date=$dateofinvoice; 
    return $this->render('InvoicesInvoicesBundle:Invoices:invoicepreview.html.twig', array(
    'companyname' =>$companyname, 
    'companyaddress' => $comanyaddress, 
    'companypobox' => $companypobox, 
    'companycity' => $companycity, 
    'companycountry' =>$companycountry, 
    'firstname' => $firstname, 
    'lastname' => $lastname, 
    'address' => $address, 
    'city' => $city, 
    'country' => $country, 
    'notes' => $notes, 
    'phonenumber' => $phonenumber, 
    'date' => $date,    
    )); 
} 

回答

2

有没有必要在你的控制器如此严重分裂出来的结果。另外通过做$ invoices [0],你显然只是从第一个结果中获取数据。

只需将发票变量传递给模板并在树枝中循环。

//controller 
... 
return $this->render('InvoicesInvoicesBundle:Invoices:invoicepreview.html.twig', array(
    'invoices' => $invoices 
)); 

{# twig template #} 
{% for invoice in invoices %} 
    {# render any data you want here with the required html #} 
    {{ invoice.companyName }} 
    {# ... #} 
{% endfor %}