Search code examples
cakephppdf-generationfpdf

Get View Output In CakePHP 2.x Model


Context: I'm generating a PDF in a model callback (afterSave). I found a library I'm comfortable with called FPDF. I'm adding the FPDF class as a vendor.

So, without going into too much detail, essentially, once all checks have been completed for a particular contract application, the app needs to prepopulate a PDF file and attach it to an email.

I can figure everything out except how to generate the PDF in the model. I want to use a view to pass view vars to so that I can populate the template file and use the FPDF class to save a PDF file.

This file will in turn be attached the automated email and sent to the applicant.

So the flow is:

  1. Once all checks have been complete (via crons and a CakePHP Shell), we trigger a function inside the model afterSave callback.
  2. The function performs some logic and determines whether a declined or approved email should be sent.
  3. If approved, then a PDF is generated using a view file and saved in /Views/pdf/
  4. This file is attached to CakeEmail object and sent.

It's just the view rendering part here that I'm stuck with:

3. If approved, then a PDF is generated using a view file and saved in /Views/pdf/

How can I populate a view file with view variables and return the result into a variable?

For example, think of how the CakeEmail class does it with the CakeEmail->template('example') function......

Any ideas?


Solution

  • The answer is to construct your view class manually:

    $view = new View(null, false);
    $view->set(compact('variable1', 'variable2'));
    $view->viewPath = 'ViewFolder';
    $output = $view->render('view_file', 'layout');