Today's the day: Write your first Visualforce email template!
I shied away from Visualforce email templates for much longer than I should have. Mostly because there was never a burning need for me to create anything. Then, two situations arose that called for some snazzier email templates than plain text could provide. Time to write some Visualforce!
Visualforce templates are good for when you want to render information conditionally and/or you want to show a list of related records. You can't render information conditionally in a plain text email or HTML email. And you certainly can't show a list of records.
Read on for two examples and code samples that you can copy + paste!
The Conditional Render
I do best with real world examples, so here's an example of a plain text email that needs a serious refresh:
V.1: Lots of superfluous information.
This email gets the job done but is missing a few things: Clear formatting that explains what the user should be looking at. Usage of "1" instead of "Yes" β it's not fair to assume that your users will understand a boolean value. There are no notes about the lead's marketing activity yet that label is there.
V.2: Cleaner, strategic bolding, and only rendering information that matters to the user.
Let's dig into the nuts and bolts of the code that fuels this email.
The code sample for the conditional render is available in this GitHub Gist. The key elements: email setup tags, lead merge fields, <apex:outputLink> for record links, <apex:outputPanel> with rendered attribute for conditional rendering, and boolean field checks to show or hide sections.
The List of Related Items
Another good Visualforce email use case β what if you wanted to show a list of records related to an object, such as opportunity line items? Completely doable with the <apex:repeat> component.
Here's an example of an email that we send internally to another department. The parent object is called a Project and the child records are Project Tasks:
The code for the related items template is available in this GitHub Gist. The <apex:repeat> component loops over related records and renders them in a table.
If you try to build a template, let me know in the comments!
Further reading:
- Creating a Visualforce email template (Salesforce docs)
- Not so scary VF templates for admins (Jan Vandevelde's blog)
- apex:outputPanel render logic (StackExchange post)
Thanks to Jan Vandevelde and Peter Churchill for their help while I tackled these two email templates. βοΈ