Getting Started with Process Builder – Part 49 (Running Lead Assignment Rules From Process Builder)

Getting Started with Process Builder – Part 49 (Running Lead Assignment Rules From Process Builder)

Last Updated on November 1, 2021 by Rakesh Gupta

To understand how to solve the same business use case using Salesforce Flow. Check out this article Getting Started with Salesforce Flow – Part 77 (Running Lead Assignment Rules From Salesforce Flow).

Big Idea or Enduring Question:

How do you run the lead assignment rule from the process builder? 

Lead assignment rules allow us to automatically assign Leads to the appropriate queue or user. A Lead assignment rule consists of multiple rule entries that define the conditions and order for assigning cases. From a Salesforce User interface, a user can trigger assignment rules by simply checking the Assign using the active assignment rules checkbox under the optional section.

The problem arises when you need to insert or update the Leads from Process Builder and wants to trigger assignment rules. Using the Process Builder, a Lead will be inserted or updated but the assignment rule will not be triggered as there is no check box to use the organization’s assignment rule or a prompt to assign using the active assignment rule. Let’s start with a business use case.

Objectives:

After reading this blog post, the reader will be able to:

  • Running the lead assignment rules from process builder  
  • Understand @InvocableMethod Annotation
  • How to call an Apex method using Process Builder 

Business Use Case

Pamela Kline is working as a System administrator at Universal Containers (UC). She has received a requirement from the management to update the following Lead fields when Lead Source changed to Partner Referral.

  • Status = Working – Contacted
  • Rating = Hot

As data changed by the process, she wants to fire the assignment rule as soon as the process updates the lead record.

Automation Champion Approach (I-do):

While this can be solved using various automation tools like Apex or Flow and Apex, we will use Process Builder and call an Apex method. To call an Apex method, add the Action element to your process builder and select an Apex class with a @InvocableMethod Annotation. It means they allow us to extend the Process Builder by writing Apex code that meets certain criteria and then invoking the Apex from our Processes. If the class contains one or more invocable variables, manually enter values or reference field values from a related record. @InvocableMethod Annotation supports bulk operations. Lets begin the solution for the business use case.
In this article, we will use the call AssignmentRuleHaeder database class from Apex code. Make sure to review it. 

Before discussing it, let me show you a diagram of a Process Flow at a high level. Please spend a few minutes to go through the following Flow diagram and understand it.

Let’s begin building this automation process.

Guided Practice (We-do):

There are 8 steps to solve Pamela’s business requirement using Process Builder. We must: 

  1. Setup a lead assignment rule
  2. Create an Apex class and test class
  3. Define process properties
  4. Define evaluation criteria
  5. Define process criteria
  6. Add action – update records
  7. Set time for actions to execute
  8. Add action – call an Apex class

Step 1: Setting Up Lead assignment Rule

  1. Click Setup.
  2. In the Quick Find box, type Lead Assignment Rules.
  3. Click on the Lead Assignment Rules | New button
  4. Now create an assignment rule, as shown in the following screenshot:

Step 2: Create an Apex class and Test class   

Now, we have to understand a new Apex annotation i.e. @InvocableMethod. This annotation lets us use an Apex method as being something that can be called from somewhere other than Apex. The AssignLeadsUsingAssignmentRules class contains a single method that is passing the ids of the Leads whose Lead Source changed to Partner Referral. Create the following class in your organization.

  1. Click Setup.
  2. In the Quick Find box, type Apex Classes.
  3. Click on the New button.
  4. Copy code from GitHub and paste it into your Apex Class. 
  5. Click Save.

Repeat the above steps and click the Test class. You can get the code from my GitHub repo. 

Step 3: Define Process Properties

  1. Click Setup.
  2. In the Quick Find box, type Process Builder.
  3. Select Process Builder, then click New.
  4. Name the Process and click the Tab button. The API Name will populate. 
  5. As a best practice, always input a description
  6. The process starts when A record changes.
  7. Click Save.

Step 4: Define Evaluation Criteria

  1. Click on the Add Object node to begin selecting the evaluation criteria.
  2. Select the Lead object from the dropdown list.
  3. Start the process when a record is created or edited.
  4. Click Save.

Step 5: Define Process Criteria

  1. Click the Add Criteria node to begin defining the process criteria.
  2. Name the criteria.
  3. The criteria should execute actions when the conditions are met.
  4. Set Conditions
    1. Row 1
      1. Field: Lead | LeadSource
      2. Operator: Equals
      3. Type: Picklist
      4. Value: Partner Referral
  5. Select All of the conditions are met (AND)
  6. Click Advanced
  7. Select Yes to execute the actions only when specified changes are made to the record.
  8. Click Save.

The reason why we would select the Yes checkbox for the question — Do you want to execute the actions only when specified changes are made to the record? — is to allow the Process Builder to execute the actions only if the record meets the criteria now, but the values that the record had immediately before it was saved didn’t meet the criteria. This means that these actions won’t be executed when irrelevant changes are made.

Step 8: Add Action – Update Records

  1. Below Immediate Actions, click Add Action.
  2. For Action Type, select Update Records
  3. Name the action.
  4. Select the option Select the Lead that started your process record type. 
  5. The criteria for updating records should be No criteria  – just update the records! 
  6. Set new field values for the records you update: 
    1. Row 1:
      1. Field: Status
      2. Type: Picklist
      3. Value: Working – Contacted 
    2. Click Add Row
    3. Row 2:
      1. Field: Rating
      2. Type: Picklist
      3. Value: Hot
  7. Click Save.

Step 7: set time for actions to execute

Because of the trigger and order of execution, the next task is to set the time for scheduled action (Apex). For this click on Set Schedule available under Scheduled actions

  1. Below Scheduled Actions, click Set Schedule.
  2. Set Field Values:
    1. Row 1:
      1. 0
      2. Hours
      3. After
      4. LastModifiedDate
  3. Click Save.

Step 8: Add Action – Quick Actions

  1. Below 0 Hours After LeastModifiedDate Scheduled Actions, click Add Action.
  2. For Action Type, select Apex
  3. Name the action.
  4. Select Apex class – AssignLeadsUsingAssignmentRules.
    1. Set Apex variables: 
      1. Row 1
        1. Field: LeadIds
        2. Type: Field Reference
        3. Value: Lead | Id
  5. Click Save.

Almost there! Once everything looks good, click the Activate button. 

Proof of Concept

Now onwards, if a business user updates the Lead Source to Partner Referral, Process Builder will automatically update Status, Type, and Assign it to the right user or queue based on the lead assignment rule. 

  1. Currently, the lead Beverly Burks is Open and the Lead Source is Blank as shown in the following screenshot:
  2. Now we update the Lead Source to Partner Referral and wait for a minute to see the process builder magic.

Formative Assessment:

I want to hear from you!  

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? 

Let me know by Tweeting me at @automationchamp, or find me on LinkedIn.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

Preferred Timing(required)

31 thoughts on “Getting Started with Process Builder – Part 49 (Running Lead Assignment Rules From Process Builder)

  1. Thanks so much for this solution. Is anyone else getting an apex error for this:

    “An Apex error occurred: System.QueryException: List has more than 1 row for assignment to SObject”

  2. Hi Rakesh,
    Thanks for this article. Can we repurpose this to create cases though community ? Currently case assignment rules don’t trigger for cases created through community.

  3. Can you suggest if and how the Apex Code should change if my PB is triggered by a Task whose WhoID is a Lead (ie ID starts with 00Q)? Everything else in my PB works (e.g. changing the Lead Record Type). Yet my Lead Assignment Rules are not triggering. I only have one Rule Entry so it’s easy to tell it’s not triggering.

    1. As per the understanding, there is no need to modify the Apex class. Could you please send me an email (infoatAutomationChampiondotcom) with all the screenshots and I will take a look at it.

  4. I love this unfortunately I am not getting the expected result . Instead of going through our Lead Assignment rules (round robin) it is falling into our default lead owner catch all (the sales manager)

    1. First, make sure that Process is active and it fulfills the entry criteria.

      Second, please explain your use case in detail.

      1. Process is active.

        We use Pardot with SalesForce. When the Pardot Score reaches thirty the lead is created with a status of “Prospect” and owned by a queue called Fishing.

        When a lead reaches a score of 100 Pardot updates the status to MQL (Marketing qualified Lead) but cannot run lead assignment rules.

        I created the Apex Class as above (copy and paste).

        Then I created a Process Builder flow:
        Object: Lead – when a record is created or edited.
        Criteria: Lead Status equals Picklist “MQL”

        Immediate action is left blank because we do not need to change any fields.

        Scheduled Action 0 hours after LastModifiedDate.

        Action “Run lead assignment rule
        Apex Class AssignLeadsUsingAssignmentRules (Copied from above)

        Set Apex Variables
        Field LeadIDs Type Reference Value {Lead}.Id

        For my test I had a Lead with a status of Prospect and in our Fishing “Queue”.
        I updated the status to MQL.

        I refreshed after a few minutes and the lead owner changed to Chris. (the fact it is changing is good)

        Unfortunately Chris is NOT in our Lead Assignment rules, (Which are 5 Round Robins).
        Under Lead Settings we have Lead Queue Setting “The queue or user that will own a lead when assignment rules fail to locate an owner: *when a lead is saved with the auto-assign checkbox selected * when a lead is captured online. So somehow the lead assignment is not working and Chris is the Default Lead Owner.

  5. Hi Rakesh,

    We have implemented the same for our Lead assignment rules, The problem was we were not getting any email notification.
    After activating the critical update,(Stop Automated Field Updates from Suppressing Email Notifications) we started getting the email notifications (multiple instead of one) and there are no email alerts other than this.

    Now the issue is we are getting 2-3 email notifications instead of one notification.

    Can you suggest something on this.

    Thanks
    Rajni

    1. Sorry, I have implemented this for execute assignment rule from process builder. Now from where these email alerts comes into the picture?

  6. HI Rakesh,

    This is good!

    I have implemented this on change of a number field on lead object, Lead type is changed. After this leads are required to follow the assignment rule as per the code I have used provided here. The leads setting up the right correct queue after update as lead owner, however, the leads are not getting passed on to queue members.

    All this process is for update records

    Can you suggest on possible reasons.

    Thanks
    Nitesh

  7. This is great! However, once I’ve created the process, I can’t create a new lead. I get a “Workflow Action Failed to Trigger Flow” error. Is there anything in the new releases that requires any change to code?

  8. Thank you Rakesh. I added the following element to your test class:
    AND isActive=true

    The line will look as follows:
    User userToCreate = [Select id from user where profile.name=’System Administrator’ AND isActive=true Limit 1];

    This helped me avoid creating leads where the owner was an inactive user.

  9. Rakesh,

    Why can’t I select the Apex class as an immediate action, instead of a Scheduled Action? Immediate actions lets you select Apex as a type of action, and why I try that… I get an error. It works perfectly as a schedule action, though.

  10. Hi Rakesh, this is explained very cleary. It’s great !
    I tried that in order to trigger Case Assignment Rules. However, I’m always getting an error.
    In the Apex class, I substituted Lead by Case and Leads by Cases.
    Here is the error, If you have any idea?

    An error occurred at element myWaitEvent_myWait_myRule_1_event_0_SA1 (FlowActionCall).
    An Apex error occurred: System.QueryException: List has no rows for assignment to SObject

    […CAN SEND YOU MORE/screenshots via email]

    WAIT: myWait_myRule_1
    Wait event myWaitEvent_myWait_myRule_1_event_0 occurred.
    The following values from the event were assigned to flow variables.
    None.
    DECISION: myPostWaitDecision_myWaitEvent_myWait_myRule_1_event_0
    Executed this outcome: myPostWaitRule_myWaitEvent_myWait_myRule_1_event_0
    Outcome conditions: and
    1. {!myVariable_current.LastModifiedDate} (12/03/2016 18:06) Is null false
    Logic: All conditions must be true (AND)
    ASSIGNCASEUSINGASSIGNMENTRULES (APEX): myWaitEvent_myWait_myRule_1_event_0_SA1
    Inputs:
    None.

    THE APEX CLASS:
    public class AssignCaseUsingAssignmentRules
    {
    @InvocableMethod
    public static void CaseAssign(List CaseIds)
    {
    Database.DMLOptions dmo = new Database.DMLOptions();
    dmo.assignmentRuleHeader.useDefaultRule= true;

            Case Cases=
    

    [select id from case where case.id in :CaseIds];
    Cases.setOptions(dmo);
    update Cases;
    }
    }

  11. Rakesh – Love, love, love this! I was just coding a trigger do this, but process builder is much better for maintenance of the business logic that kicks off the invocable class… Can you please post the test class to github? Thanks, Tom

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Automation Champion

Subscribe now to keep reading and get access to the full archive.

Continue reading