Search code examples
phpcodeigniterpdf-generationdompdfinvoices

Passing variables from controller to view that works with DOMPDF in CodeIgniter


Best regards! Today I'm with an issue trying to generate invoices in PDF with DOMPDF.

Let's explain: I have a view that i select the invoice id. When I click the "generate PDF" button it goes this way:

(takes you to controller)

foreach ($this->input->post('check') as $key)
    {

    $testLayout = load_modulo('bankX', 'invoice_bankX'); //here I call the file in views dir(bankX) and the view inside the file (case 'invoice_bankX') that brings me the bank invoice layout
    $filename = 'invoice_'.$key;
    pdf_create($testLayout, $filename, TRUE);

    }

(the load_modulo function)

function load_modulo($modulo = NULL, $tela = NULL, $diretorio = 'panel') {

$CI = & get_instance();

if ($modulo != NULL) {

    return $CI->load->view("$diretorio/$modulo", array('tela' => $tela), TRUE);
} else {


    return FALSE;
    }
}

(the pdf_create function)

function pdf_create($html, $filename = '', $stream = TRUE) {
require_once("dompdf/dompdf_config.inc.php");

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();

if ($stream) {
    $dompdf->stream($filename . ".pdf");
} else {

    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);


}

Now knowing that I have more data to pass through to the 'invoice_bankX' view (I need 1 var that retain the bank and client values that I can callback in this view to mount the invoice with the client and store datas )

i.e.

$invoiceData = array();

$invoiceData['invoice_number'] = 344;

$invoiceData['client_name'] = 'John Masters';

Because this way I can pass the values to mount the invoice correctly. Anyone knows how to?

*note - right now, if I click the button to generate invoice(PDF), this works. But the invoice comes with the static data that I wrote to test


Solution

  • I found a way to do this by setting the number of the invoice on session. The controller now looks like this and it works:

    foreach ($this->input->post('check') as $key)
        {
    
            $dataInvoice = array('invoice_number' => $key);
            $this->session->set_userdata($dataInvoice);
    
            $testLayout = load_modulo('bankX', 'invoice_bankX');
            $filename = 'invoice_'.$key;
            pdf_create($testLayout, $filename, TRUE);
    
        }
    

    So that way I could call at the view the

    $invoice_number = $this->session->userdata('invoice_number');
    

    and do all the queries that i want