Search code examples
mysqlsymfonydoctrine-ormdql

How to set loop on query result and then pass to twig file?


I want to add for loop for populating data in variables in php.So i get rows of query result.how to apply loop and get number of rows of query result in dql?

Here is my code:

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

Solution

  • There's no need to split out your results so heavily in your controller. Also by doing $invoices[0] you are obviously just getting data from the first result.

    Simply pass the invoices variable into the template and loop through it in twig.

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