top of page
Search

Apex: Assign owner using Lead Assignment Rules

Updated: Jun 26, 2020

Lead Assignment Rules are really important in your Org if you want to properly manage your sales pipeline. Most companies are using some kind of round-robin where every lead is assigned to a different Sales Rep or they are using some rules based on territory.


When you manually edit a lead, there's a small checkbox, allowing you to assign the owner based on those rules, but sometimes you need to massively create/update/reassign leads.


Here's a really simple script you can use to apply the rules in Apex!

1. Create a Database.DMLOptions object where you can set the assignmentRuleHeader.useDefaultRule property to true. That's the magic property that will tell Salesforce to apply the Assignment Rules.

2. Use a simple SOQL query to get the leads where you want to update the owners.

3. Use the setOptions function on lead. That will make Salesforce use the options we created before when the database operation will be called on that lead.

4. Update the lead collection.


I can easily remember a few scenarios where that simple code would have been useful. I hope it can save you some time too, let me know in the comments if it did!


Visit the Salesforce documentation for more information about the Database.DMLOptions object!

Recent Posts

See All

Improve your Apex Testing Performance

It's Friday afternoon. You just deployed a new feature to your Salesforce Org. Something is clearly wrong with it. Your users are complaining, your boss is calling you in panic. You need to fix it NOW

TrailheaDX 2020

For this year's edition of TrailheaDX, because of the COVID-19 pandemic, Salesforce transformed the event into a single day fully remote event. The event is split into 4 separate trails: Developer, Ad

Salesforce <3 Codespace

A few weeks ago, Microsoft held Build 2020, the developer focused conference, where they announced Codespace. Codespace basically allows you to run a complete version of VSCode directly from your bro

© 2020 by Marc The Code

bottom of page