lead assignment rules salesforce apex

How to Re-run Salesforce Lead Assignment Rules: Process Builder & Apex

Note:  On Sep 23, 2021, Salesforce announced they’re deprecating Process Builder in “Summer 2022.”  And they cautioned , “the best way for you to future-proof your organization is to move your automation to Flow.”  This Process Builder tutorial is still accurate, but we recommend reading and following the Flow tutorial instead.

Salesforce Lead assignment rules are a powerful tool to make sure that Leads are assigned to the appropriate user or queue for follow up. They also allow marketers to get and stay out of the business of trying to maintain sales territory logic within their Marketing Automation Platform (MAP).

When a new Lead is created, Salesforce will use the logic you’ve configured to assign the record to the appropriate user or queue. But what if you need to re-run that logic on existing records? If you only need to do this for a single Lead record, the solution is as simple as editing the record and selecting the optional “Assign using active assignment rule” checkbox.

>> Related: 6 Ways to Handle Those Pesky Spambot Clicks in Marketo <<

Here’s an example of what that looks like:

Edit Lead Screenshot with Assign box checked

If you need to do a one-time batch reassignment of a number of records, you can export the relevant Lead Ids and use the Apex Data Loader to trigger assignment rules to fire. You can grab the ID of the appropriate Lead Assignment Rule from the URL bar when viewing the rule in Setup. It will always start with the prefix “01Q”.

Assignment Rule Id from URL bar

Re-Run Salesforce Lead Assignments

There are times where you want to re-run assignment rules automatically under certain conditions. For example, you may assign Leads under a certain Lead Score to a Queue. When the Lead Score increases over the threshold, you then want to re-run assignment rules to assign to an inside sales rep for follow up.

In order to accomplish this, we can use the extremely powerful combination of Process Builder and an Apex Invocable method. This allows you to take advantage of the power of Apex with the flexibility to declaratively (clicks, not code!) control the logic of when to re-run the assignment rules without having to edit any code.

Using Apex for Salesforce Lead Assignment Rules

Let’s start with the code. Since we’re writing code here, we’ll need to start in a sandbox org first before deploying to production. You’re smart and already knew that you’d NEVER make changes in production without first testing in a sandbox ( right?! ), but in this case, Salesforce doesn’t trust you either way and forces you to write your code in a sandbox org before moving to production.

We’ll be creating an Apex class with a single method with the @InvocableMethod annotation, which allows us to call our Apex from within a Visual Flow or Process. The method accepts a single parameter (a list of the Lead Ids to be assigned) that you’ll pass into the method from your Process.

That’s it. Just those four lines are all you need in your code. The rest of your logic for when to actually fire the assignment rules will be configured in Process Builder.

Now, in order to actually deploy this to your production org, you’ll also need to create a test class to cover your code and ensure that it functions as expected in your environment. A sample test class might look like this, but this is extremely basic. I suggest working with a developer to make sure you’re doing everything properly and accounting for any additional requirements specific to your Salesforce instance.

Using Salesforce Process Builder for Salesforce Lead Assignment Rules

Now that we have our code to reassign our Leads, we’ll create our declarative logic of when to fire it using the Process Builder.

1) Create a new Process by searching for the Process Builder under Setup and clicking the New button in the top right. Give your process a name, and set the option for “The process starts when” to “A record changes” as shown in the screenshot below.

New Process Window

2) Select the Lead object for your Process and start the process when a record is created or edited.

lead assignment rules salesforce apex

3) Click on Add Criteria, and give your criteria a name. In this example, we’ll be exploring the earlier use-case of wanting to re-assign Leads after they meet a certain Lead Score. We’ll select “conditions are met” and set the condition that the Lead Score is greater than or equal to 100. Under the advanced section, we’ll select the option to only execute the actions when specified changes are made to the record. This means that we’ll only execute the actions if the record previously did not meet the criteria but now does after being updated.

Process Action Criteria

4) Without getting into too much detail, because of Triggers and Order of Execution , we can’t call our code in an immediate action. Instead, we’ll create a scheduled action to call our Apex method. In this case, we want the logic to execute as quickly as possible, so we’ll set the schedule for 0 hours from now.

Process Set Schedule

5) Once saved, we can create our scheduled action. Click Add Action, and select the Action Type Apex. Give your action a name, and select the Apex class you created earlier. Set the Apex Variables leadIds using the Field Reference of the Lead Id that started the process.

Scheduled Action

6) After saving, you can activate your process and test in your sandbox to ensure functionality before deploying to your production org. Since the code is fired under a scheduled action, there is a slight delay before the reassignment happens. In my experience, this is usually less than two minutes, but you can monitor this under Setup > Flows and viewing the Paused and Waiting Interviews section.

Scheduled Action Monitoring

Once you’ve tested and are satisfied that everything is working properly, you can deploy this up to your production org and start taking advantage of this right away. The nice part about this particular approach is that if your requirements change—for example if your Lead Score threshold changes to 150 instead of 100—you can change the logic in your Process without having to touch any code.

Ready to unleash the full power of Salesforce, without hiring another full time employee?

Learn about our Salesforce admin support package .

You might also like

lead assignment rules salesforce apex

How to Dynamically Require Fields Using Salesforce Dynamic Forms

lead assignment rules salesforce apex

Salesforce Package: Stamp UTM Parameters on Campaign Members

lead assignment rules salesforce apex

How to: Convert Salesforce Process Builders to Flows

Subscribe to sponge's newsletter.

Get tips, tutorials, best practices, and other cool stuff delivered to your inbox every quarter.

Get a System Audit

Whether you inherited a new instance or just want a second opinion, we'll dive in and benchmark your tech stack.

Download Resource

Use this form to recieve your free resource in your inbox today!

Setting Lead Assignment Rules with Apex

If you want to create a new Lead via Visualforce or web form with Apex it’s very possible you could overlook the Assignment Rules.  As you might know, it’s not even always obvious on the native Lead creation layout.  Notice the lower left corner checkbox in the screenshot below.

Assignment Rule - Salesforce

To enforce Assignment Rules in Apex you’ll need to instantiate the Database.DMLOptions class, set the useDefaultRule property of assignmentRuleHeader to True, and finally call a native method on your Lead called setOptions, with the Database.DMLOptions instance as the argument. The code below demonstrates:

Have questions? Let us know in a comment below, or contact our team directly. You can also check out our other posts on Apex .

About The Author

' src=

2 thoughts on “Setting Lead Assignment Rules with Apex”

' src=

Great post! It solve my problem. Thanks!

' src=

Can someone one send me a samlpe Apex trigger?I tried all the operations and keep getting error when triggered. Some of the errors are below:System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.myTrigger: System.FinalException: Record is read-only: Trigger.myTrigger:

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Automation Champion

Automation Champion

Automating Salesforce One Click at a Time

Running Lead Assignment Rules From Salesforce Flow

Running Lead Assignment Rules From Salesforce Flow

Last Updated on February 14, 2022 by Rakesh Gupta

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

Big Idea or Enduring Question:

How do you run the lead assignment rule from the Salesforce flow? 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 Salesforce Flow and wants to trigger assignment rules. Using the Salesforce Flow 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:

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 Referra l .

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):

lead assignment rules salesforce apex

Guided Practice (We-do):

There are 4 steps to solve Pamela’s business requirement using Salesforce Flow and Apex. We must:

Step 1: Setting Up Lead assignment Rule

lead assignment rules salesforce apex

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.

lead assignment rules salesforce apex

Step 3.1: Salesforce Flow – Define Flow Properties for Before-Save Flow

lead assignment rules salesforce apex

Step 3.2: Salesforce Flow – Using Decision Element to Check the Lead Source

Now we will use the Decision element to check the lead source to ensure that it is equal to Partner Referral.

lead assignment rules salesforce apex

Step 3.3: Salesforce Flow – Adding an Assignment Element to Update Rating and Status

lead assignment rules salesforce apex

lead assignment rules salesforce apex

Step 4.1: Salesforce Flow – Define Flow Properties for After-Save Flow

lead assignment rules salesforce apex

Step 4.2: Salesforce Flow – Add Scheduled Paths

lead assignment rules salesforce apex

lead assignment rules salesforce apex

Step 4.3: Salesforce Flow – Adding an Action to Call Apex class to Trigger Lead Assignment Rule

lead assignment rules salesforce apex

lead assignment rules salesforce apex

Proof of Concept

Now onward, 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.

lead assignment rules salesforce apex

Monitor Your Schedule Flow

To monitor Flows that are scheduled, navigate to the following path:

lead assignment rules salesforce apex

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.

Submit Query!

Similar Posts

lead assignment rules salesforce apex

Create Lookup with Dynamic Forms for Flow

lead assignment rules salesforce apex

Create Filtered Lookup with Choice Lookup

lead assignment rules salesforce apex

Select Multiple Records in the Lookup Component

6 thoughts on “ running lead assignment rules from salesforce flow ”.

after the apex class fires, noticed the lead owner is assigned to default lead owner, instead of using lead assignment rule. Any clue?

Thank you for an excellent tutorial 🙂 you solved my problem! Very much appreciated

Anyone getting issues with an error on mass updates “Apex error occurred: System.QueryException: List has more than 1 row for assignment to SObject “? if each one is called individually, I don’t understand how there is more than 1 row for assignment. Sometimes I get an email with this error only to see that the trigger actually worked for the specified record so a bit odd. Thanks!

Thank you for the great tutorial. Why add the 1 minute wait? Is that just to take avoid too much synchronous automation? Or is it required for another reason?

You’re right Kevin (to make the process asynchronous).

Leave a Reply Cancel reply

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

lead assignment rules salesforce apex

Activity › Forums › Salesforce® Discussions › How To Force Lead Assignment Rule Via Apex While Updating Or Adding The Lead?

How To Force Lead Assignment Rule Via Apex While Updating Or Adding The Lead?

' src=

To enforce Assignment Rules in Apex you will need to perform following steps:

1. Instantiate the “Database.DMLOptions” class. 2. Set the “useDefaultRule” property of “assignmentRuleHeader” to True. 3. Finally call a native method on your Lead called “setOptions”, with the Database.DMLOptions instance as the argument.

// to turn ON the Assignment Rules in Apex

Database.DMLOptions dmlOptn = new Database.DMLOptions();

dmlOptn.assignmentRuleHeader.useDefaultRule = true; leadObj.setOptions(dmlOptn);

' src=

Adding some code snippet:

AssignmentRule AR = new AssignmentRule(); AR = [select id from AssignmentRule where SobjectType = 'Lead' and Active = true limit 1];

//Creating the DMLOptions for "Assign using active assignment rules" checkbox Database.DMLOptions dmlOpts = new Database.DMLOptions(); dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;

Lead newLead = new Lead(Status = 'New') ; //Setting the DMLOption on Lead instance newLead.setOptions(dmlOpts); insert newLead ;

Log In to reply.

 alt=

Popular Salesforce Blogs

lead assignment rules salesforce apex

Turn Your Mission into a ‘Connected’ Nonprofit with Salesforce

Technological disruption is pervading every industry, and the Non-profit sector is no longer a different kettle of fish. For non-profits, where collaboration, communication, community building…

' src=

Learn How to Display Bar Chart in Salesforce Lightning Web Component

Introduction The graphical representation of information and data is known as data visualization. Data visualisation tools make it easy to see and understand trends, outliers,…

' src=

How To Manage Duplicate Records In Salesforce?

It becomes utmost important to detect potential duplicates when records are being updated in the system via integration i.e when all the records like accounts,…

' src=

Popular Salesforce Videos

Success from Anywhere with Salesforce EMEA Leaders

Success from Anywhere with Salesforce EMEA Leaders

Watch this video to learn about Success from Anywhere with Salesforce EMEA Leaders. Do let us know your opinions in the comment section.

' src=

How to Use Customer 360 | Salesforce

See how Salesforce Customer 360, our entire portfolio of technology, unites your team with company data on one integrated CRM platform, delivering the personal experiences…

' src=

Salesforce Announces New Salesforce CDP Updates | Salesforce CDP

Salesforce, one of the largest global providers of CRM solutions, launched Salesforce CDP last year. Salesforce Customer Data Platform is an enterprise customer data platform…

' src=

There was a problem reporting this post.

Block Member?

Please confirm you want to block this member.

You will no longer be able to:

Please note: This action will also remove this member from your connections and send a report to the site admin. Please allow a few minutes for this process to complete.

Stack Exchange Network

Stack Exchange network consists of 181 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How do I run the default Lead assignment rules on a Lead trigger

Here's my code stripped of the usual professional infrastructure for illustration:

And here's the usual run lead assignment code

Again for illustration, I'm just trying to trigger the autoassign rule in the lead trigger on the leads we've updated. I've tried the code in both these places and it runs, but the assignment doesn't kick it. If I do this outside the Lead and then trigger it, it works. So I must not be putting it in the right place or doing it correctly. What's the right place to set this option?

This guy just gave up. Need help with Apex Trigger to run Lead Assignment Rules

Here's an attempt I did which seems to have worked, but I don't fully understand its implications

I did't understand the recursive function because the recursiveUpdate was, at the very highest, in the scope of the trigger and when you call Database.update, it would be a new boolean in a new instance of the trigger, which means the guard would guard nothing because it's above the reassignment in the new instance. The only way I could understand it is if the boolean was above all the triggers and would prevent other triggers from firing their runAssignmentRules because a prior trigger already made it true. Anyway, my solution still feels to good to be true, so I'm going to keep testing.

Henrietta Martingale's user avatar

The assignment rule that will run is fixed at the instant the DML operation starts. In other words, by the time your trigger has started running, it is far too late to set an assignment rule. You would instead need to make a recursive update. Further, there are known limitations on the sObject.setOptions method; it would be recommended to use the Database.update(sObjects, dmlOptions) method. This also allows us to bulkify the logic.

First, we check if we're already running recursively, and if so, we return early. Next, we set up the DML options we want to use and set the recursive flag to avoid infinite loops. After that, we run the DML operation. Finally, we reset the recursive flag in order to avoid disabling our trigger logic for legitimate repeat calls (partial save logic, more than 200 records in a transaction, multiple DML operations in the same transaction, etc).

Also, this logic needs to be run in an after update/after insert context. In a before insert/before update context, the record either doesn't yet have an ID, or will be locked against further DML operations.

sfdcfox's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged apex trigger assignment-rules lead-assignment or ask your own question .

Hot Network Questions

lead assignment rules salesforce apex

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Salesforce lead assignment rules – Salesforce Tutorials

Creating and managing salesforce lead assignment rules .

In this Salesforce tutorial we are going to learn about What is an assignment Rules , How can we create and manage Salesforce lead assignment rules, and why should we create assignment rules in Salesforce.

What is an Assignment Rule?

Assignment Rules are used to assign Leads and Cases automatically to the assigned users based on criteria. There are two types of Assignment Rules in Salesforce they are

What are Salesforce lead assignment rules?

Salesforce lead assignment rules defines the administrators to assign a lead to users and queues based on criteria. A lead can be generated either by manually or generated from the web.

What are case Assignment Rules?

Salesforce lead assignment rules defines the administrators to assign a Case to users and queues based on criteria. A Case can be generated  by manually , generated from the web to case, Email to case etc.

How to create Salesforce lead assignment rules?

Creating and Managing Salesforce lead assignment rules are very important. Let us learn how to create lead assignment rules in Salesforce.com. To create assignment rules login Salesforce and navigate to Setup | Build | Customize | Lead | Lead Assignment Rules.

Click on New Button to create new Salesforce lead assignment rule.

There are only one standard rule in our salesforce. If we create new Assignment rule in Salesforce the first standard rule will be automatically deactivated. At a single point of time only one assignment rule is active. For a single rule there can be multiple rule entries.

How to create New Rule entries in Salesforce Lead Assignment Rules.

In Salesforce we can create many rule entries for single Assignment Rule.

Learn how to create Email template in Salesforce.

We have created two Rule entries with order 1 and Order 2. In this Salesforce lead assignment rules, Generated leads will be automatically assigned to the country United State and Country United Kingdom.

Conclusion :

In this Salesforce Tutorial we have learned about What is Assignment rule and How to create Salesforce lead assignment rules. Like wise case assignment rules are also similar to lead assignment rules.

Most Read Articles

Admin_Logo w outline.png

Run Assignment Rules in Salesforce Whenever You Want!

While Salesforce’s assignment rules allow for record assignments to be taken care of with ease, they suffer from one big pitfall. Current Salesforce functionality allows for assignment rules to be run when a record is created. But this does not allow for the freedom to choose the exact moment to have those rules trigger. They do not allow you to re-run them when specific criteria is met. Record values can quickly change, and having rules run when created or edited may not always suit your requirement.

Also, when you create records via Lightning quick actions - Salesforce does not allow for assignment rules to be triggered for records created this way.

This is where the Salesforce Assignment Plugin opens that functionality up for you. With the Assignment Plugin, you can trigger assignment rules as often as necessary directly from process builder, flow, or custom code.

Here, we show how Lead assignment rules can be re-triggered, using the Assignment Plugin, when the Lead’s Pardot Score goes above 50.

First, download the Assignment Plugin from the App Exchange. This can be downloaded here.

Once that is done, you can add it to your process builder.

Create a new process builder node and add your criteria. Ours is very simple, it triggers once the Pardot Score field is above 50.

lead assignment rules salesforce apex

Next, in your process builder action, choose Apex. From the dropdown list of Apex classes find the “Run_Assignment” options. Note the different classes that can be chosen:

Invocable_StandardAssignment - executes your assignment rules in an immediate action

Invocable_StandardAssignmentV2 - executes your assignment rules immediately and allows you to trigger the email notifications configured within your assignment rules

Invocable_StandardAssignmentFuture - executes your assignment rules as a scheduled action

Invocable_StandardAssignmentFutureV2 - execute your assignment rules as a scheduled action and allows you to trigger the email notifications configured within your assignment rules

For our process, we use the Invocable_StandardAssignmentV2.

lead assignment rules salesforce apex

The variables for the invocable class are as follows:

triggerUserEmail - allows for emails to be sent to users within your org

triggerAutoResponseEmail - allows for auto response triggers to run during the assignment

triggerOtherEmail - allows for emails to be sent outside of the org

recordId - a reference to the record’s id

Since we are not triggering any emails in our process, we also could have used the Invocable_StandardAssignment class.

You can now save and activate your process. Now, whenever your Lead’s Score increases to above 50, your assignment rules will calculate as per their criteria and your Lead record will automatically be routed to the correct owner.

You can utilize this plugin with a wide range of processes and can even use it within your flow to get the full extent.

IMAGES

  1. How to Re-run Salesforce Lead Assignment Rules with Process Builder & Apex

    lead assignment rules salesforce apex

  2. Salesforce lead assignment rules

    lead assignment rules salesforce apex

  3. Salesforce lead assignment rules

    lead assignment rules salesforce apex

  4. Salesforce lead assignment rules

    lead assignment rules salesforce apex

  5. Salesforce lead assignment rules

    lead assignment rules salesforce apex

  6. Salesforce lead assignment rules

    lead assignment rules salesforce apex

VIDEO

  1. AIOU Autumn 2022 LMS Assignment Rules

  2. Salesforce Apex Basic

  3. Salesforce / Define Sharing Rules

  4. Master Summary Reports in Salesforce with this Beginner Tutorial

  5. Apex Assignments

  6. Lead & Case Assignment Rules ! Salesforce Admin ! Salesforce trail head

COMMENTS

  1. How to Re-run Salesforce Lead Assignment Rules

    Salesforce Lead assignment rules are a powerful tool to make sure that Leads are assigned to the appropriate user or queue for follow up. They

  2. Setting Lead Assignment Rules with Apex

    If you want to create a new Lead via Visualforce or web form with Apex it's very possible you could overlook the Assignment Rules.

  3. Running Lead Assignment Rules From Salesforce Flow

    A Lead assignment rule consists of multiple rule entries that define the conditions and order for assigning cases. From a Salesforce User

  4. How To Force Lead Assignment Rule Via Apex While Updating Or

    Hi,. To enforce Assignment Rules in Apex you will need to perform following steps: 1. Instantiate the “Database.DMLOptions” class.

  5. Run Case Assignment Rule from Apex

    From a standard UI, a user can trigger assignment rules by simply checking the "Assign using active assignment rules" checkbox under the

  6. Assignment Rules

    Assignment rules automate your organization's lead generation and support processes. Use lead assignment rules to specify how leads are assigned to users...

  7. Lead Assignment Rules

    Assignment rules automate your organization's lead generation. Learn how to create and use lead assignment rules to specify how leads are

  8. How to Trigger THE Lead Assignment Rule from Flow Builder

    Want to learn more about salesforce join me at https://sfdcpanther.com Hello #Trailblazers,In this video, we will talk about how to trigger

  9. How do I run the default Lead assignment rules on a Lead trigger

    The assignment rule that will run is fixed at the instant the DML operation starts. In other words, by the time your trigger has started

  10. Salesforce lead assignment rules

    Salesforce lead assignment rules defines the administrators to assign a Case to users and queues based on criteria. Multiple rule entries can.

  11. Run Assignment Rules in Salesforce Whenever You Want!

    You can now save and activate your process. Now, whenever your Lead's Score increases to above 50, your assignment rules will calculate as per their criteria