Earlier today I had a need in one of my ColdBox applications to create printable versions of all my pages. A pretty normal request. What I like to do for these applications is have a single Event Handler called “Display” that manages all of the front-end calls, so all of the Event Methods that I would want to print were all in the same Handler. There are a mixture of methods in my front-end handler, some of them pull their content from the DB, some of them use a view that has content coded into it, such as forms. Some pages have views that render news items and things of that nature, so the methods are all pretty different. This led me to believe that creating this print functionality was going to be a bit tedious at best.I didn’t want to create new print methods for each existing method just to overwrite the layout using the print layout. Way too much coding and seemed a bit overkill. So after talking to Luis Majano about overriding layouts, here is what I came up with. Its very simple, quick to implement and works like a charm!
Here is how I coded my “Print This Page” link.
Print This Page
Notice I call a single event called Display.print and Im passing a variable called page that consists of the current event from ColdBox that Im displaying. We are going to use that variable to run our existing methods.
Now here is my Print event handler. Notice its pretty simple.
Basically, all Im doing is running the event thats passed in as the page variable and setting the layout to my printable layout. Super easy! This one method handled every front-end method that I have in my app. Now obviously Im not passing around any other url variables in my application. This would make things a bit more complicated but you could still handle it with this same method.