Invocable Apex Methods



Within Salesforce, it’s very frustrating that automatically generated emails (via workflow rules or the process builder) don’t automatically generate an activity record for the lead or contact to whom they’re sent. 

We’ll solve this problem today and in the process learn how to use “invocable” Apex to extend the capabilities of the process builder!

Video Breakdown

In the video we will…

  • Examine a shortcoming of the Salesforce platform out of the box
  • Set up an email alert via Workflow Rule
  • Set up and email alert via Process Builder
  • Build a simple invocable Apex method to extend the Process Builder and solve the aforementioned shortcoming

Code Snippets From the Video

Invocable Apex Class

global class Invocable_SendEmailToLead {

    global class DataWrapper {
        @InvocableVariable(label='Lead Record Id' required=true)
        public String recordId;
        @InvocableVariable(label='Email Template Id' required=true)
        public String emailTemplateId;
    @InvocableMethod(label='Send Email to Lead')
    global static void sendMailToLead (List<DataWrapper> passedData) {
        // Send the mail!

        for (DataWrapper dw: passedData) {
            // Get the relevant template based on supplied ID.
            EmailTemplate selectedTemplate = [SELECT Id FROM EmailTemplate WHERE Id =: dw.emailTemplateId];
            // Create the SingleEmailMessage object and set the target and template.
            Messaging.SingleEmailMessage mailToSend = new Messaging.SingleEmailMessage();
            // Send that email and debug the results!
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(new List<Messaging.Email> { mailToSend });

Just a quick note about the above code; ideally we don’t want to run a query whatsoever within the loop. For efficiency’s sake we should pull that query above the loop. This is just an example, so I won’t fix it here for the sake of keeping the code really simple. 

Hope this helps!

1 comment

Recent Posts