• Marketing Cloud

Experiences

Access Trailhead, your Trailblazer profile, community, learning, original series, events, support, and more.

Apex Reference Guide

Winter '25 (API version 62.0)

Search Tips:

  • Please consider misspellings
  • Try different search keywords

DmlOptions.AssignmentRuleHeader Class

Dmloptions.assignmentruleheader properties.

The following are properties for DmlOptions.AssignmentRuleHeader .

  • assignmentRuleID Specifies the ID of a specific assignment rule to run for the case or lead. The assignment rule can be active or inactive.
  • useDefaultRule If specified as true for a case or lead, the system uses the default (active) assignment rule for the case or lead. If specified, do not specify an assignmentRuleId .

assignmentRuleID

public Id assignmentRuleID {get; set;}

Property Value

The ID can be retrieved by querying the AssignmentRule sObject. If specified, do not specify useDefaultRule .

If the value is not in the correct ID format (15-character or 18-character Salesforce ID), the call fails and an exception is returned.

useDefaultRule

public Boolean useDefaultRule {get; set;}

Type: Boolean

If there are no assignment rules in the organization, in API version 29.0 and earlier, creating a case or lead with useDefaultRule set to true results in the case or lead being assigned to the predefined default owner. In API version 30.0 and later, the case or lead is unassigned and doesn't get assigned to the default owner.

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:

  • Running the lead assignment rules from Salesforce Flow
  • Understand @InvocableMethod Annotation
  • How to call an Apex method using Salesforce Flow

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 .

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

lead assignment using apex

Guided Practice (We-do):

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

  • Setup a lead assignment rule
  • Create Apex class & Test class
  • Define flow properties for record-triggered flow
  • Add a decision element to check the lead source
  • Add an assignment element to update status & rating
  • Add a scheduled path
  • Add a decision element to check if lead source changed
  • Add action – call an Apex class to invoke lead assignment rule

Step 1: Setting Up Lead assignment Rule

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

lead assignment using 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.

  • In the Quick Find box, type Apex Classes .
  • Click on the New button .
  • Copy code from GitHub and paste it into your Apex Class.
  • Click Save.

lead assignment using apex

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

  • In the Quick Find box, type Flows .
  • Select Flows then click on the New Flow .
  • How do you want to start building : Freeform
  • Object : Lead
  • Trigger the Flow When : A record is created or updated
  • Condition Requirements: None
  • Optimize the Flow For : Fast Field Updates
  • Click Done .

lead assignment using 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.

  • Under Toolbox , select Element .
  • Drag-and-drop Decision element onto the Flow designer.
  • Enter a name in the Label field; the API Name will auto-populate.
  • Under Outcome Details , enter the Label the API Name will auto-populate.
  • Resource: {!$Record.LeadSource}
  • Operator: Equals
  • Value: Partner Referral
  • When to Execute Outcome : Only if the record that triggered the flow to run is updated to meet the condition requirements

lead assignment using apex

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

  • Drag-and-drop the Assignment Element element onto the Flow designer.
  • Enter a name in the Label field- the API Name will auto-populate.
  • Field: {!$Record.Rating}
  • Add Condition
  • Field: {!$Record.Status}
  • Value: Working – Contacted

lead assignment using apex

  • Click Save .
  • Enter Flow Label the API Name will auto-populate.
  • Click Show Advanced .
  • API Version for Running the Flow : 53
  • Interview Label : Record-Trigger: Lead Before Save {!$Flow.CurrentDateTime}

lead assignment using apex

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

  • Field : Lead Source
  • Operator: Euqals
  • Optimize the Flow For : Action and Related Records

lead assignment using apex

Step 4.2: Salesforce Flow – Add Scheduled Paths

lead assignment using apex

  • Under SCHEDULED PATHS , click on the New Scheduled Path .
  • Under Scheduled Path Details , enter the Label the API Name will auto-populate.
  • Time Source : Lead: Last Modified Date
  • Offset Number : 1
  • Offset Options : Minutes After

lead assignment using apex

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

  • Drag-and-drop the Actions element onto the Flow designer.
  • Select the AssignLeadsUsingAssignmentRules Apex class.
  • Field: LeadIds
  • Value: {!$Record.Id}

lead assignment using apex

  • Interview Label : Record-Trigger: Lead After Save {!$Flow.CurrentDateTime}

lead assignment using 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 using apex

Monitor Your Schedule Flow

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

  • Navigate to Setup (Gear Icon) | Environments | Monitoring | Time-Based Workflow .

lead assignment using apex

  • Use the Delete button to delete the time-based Flow job from the queue.

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 using apex

Elevate Your Screen Flows with a Customizable Counter Component

lead assignment using apex

Dynamic Progress Bar for Form Completion in Salesforce Flow

lead assignment using apex

Launch a Flow from CRM Analytics Dashboard Text Widget

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

It ran repeatedly, every minute, over and over again. I was getting notification email every minute when testing. I did the same steps as you mentionned, with a record triggered flow containing the apex action.

I found that this ran repeatedly, every minute, over and over again. Was easy to spot because I modified the Apex to include sending the user notification email as well – so I was getting notification email every minute when testing.

When I updated the ‘Time Source’ in the flow scheduled path from ‘Time Source: Lead: Last Modified Date’ to ‘Time Source: When Lead is Created or Updated’ that seems to have solved the problem.

Was curious if you had the same experience or if there was some other nuance happening.

It also looks like you had originally intended to use a decision element in step 4.3 but changed that to flow entry requirements, likely because the scheduled path can’t assess the prior and current values the same way the starting node can.

Thank you for sharing your valuable feedback. I have a quick question for you: When executing the Apex class, do you utilize a Record-triggered Flow or a Scheduled-triggered 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).

  • Pingback: Getting Started with Process Builder – Part 49 (Running Lead Assignment Rules From Process Builder) - Automation Champion

Leave a Reply Cancel 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.

Type your email…

Continue reading

Product Area

Feature impact.

No results

  • What’s Service?
  • Service Setup Assistant Features
  • Customize Support Settings
  • Guidelines for Setting Business Hours
  • Guidelines for Creating Support Holidays
  • What’s a Case?
  • What’s a Case Team?
  • Create Case Team Roles
  • Predefine Case Teams
  • Set Up Email Alerts for Case Teams
  • Case Team Fields
  • Case Feed Upgrade Process
  • Create Permission Sets
  • Assign Permission Set
  • Assign Custom Profile
  • Convert Page Layouts
  • Customize the Highlights Panel
  • Configure the Case Feed Publisher
  • Case Feed View Layouts
  • Feed View Settings
  • Add the Attachment Component
  • Add Case Experts
  • Rename Actions and Feed Filters
  • Customize Feed Filters
  • Add Custom Actions
  • Add Custom Components
  • Add Actions as Console Components
  • Email Drafts
  • Enable Email Templates
  • Email Draft Approval Process
  • Email Approval Send Actions
  • Highlight External Feed Items
  • Email Notifications for Portal Replies
  • Log a Call Action
  • Apply a Default Email Template
  • Send Email Fields
  • Send Email Considerations
  • Draft Personalized Emails with Service Email Assistant
  • Understand Default Email Fields
  • Change Status Action
  • Change Owner Action
  • Close Case Action
  • Case Comment Action
  • Add Actions to the Case Page
  • Customize Case Hovers
  • Set Up Case Merge in Lightning Experience
  • Set Up a Customer Feedback Survey
  • Move Emails to a Different Case
  • Let Agents Move Emails to a Different Case
  • Create Cases
  • Clone Cases
  • View Case Lists
  • Update Multiple Cases
  • Assign Cases
  • Share Cases
  • View the Case Milestones
  • Case Comments
  • Create and Edit Case Comments on Case Detail Pages
  • Create and Edit Case Comments on Case Edit Pages
  • Use Actions to Work with Cases in Case Feed
  • Use Feed Filters in Case Feed
  • Case Feed and Related Lists
  • Find, Attach, and Email Articles with the Case Feed Articles Tool
  • View and Edit Cases from the Case Detail Page in Case Feed
  • Post on Cases and Experience Cloud Site Questions with the...
  • Printable View in Case Feed
  • In Lightning Experience
  • Work with Case Emails
  • Send and Reply to Email
  • Add Images and Files
  • Use Email Templates
  • Work with Draft Emails
  • Review and Approve Email Drafts
  • Customize with Rich Text
  • Set Up a Default No-Reply Email Address
  • Merge Fields for Cases
  • Close Cases
  • Solve Cases
  • Delete Cases
  • Merge Duplicate Cases from the Cases List View
  • Merge Duplicate Cases from the Case Record Home
  • Enable Suggested Articles to Solve Cases
  • Send Articles from Cases
  • Guidelines for Working with Cases
  • Case Fields
  • Case History
  • Case Hierarchies
  • Related Cases
  • Changes to the Cases and Case Feed Mobile App
  • Find What You Need
  • What’s Entitlement Management?
  • Setup Checklist
  • Limitations
  • Set Up Lookup Filters
  • Give Users Access
  • Create Entitlement Templates
  • Auto-Add Entitlements to Cases
  • Report on Entitlements
  • Verify Entitlements
  • Terms to Know
  • Entitlement Fields
  • Customize Page Layouts
  • Enable Feed Items
  • Set Up the Milestone Tracker
  • Limit User Updates
  • Create a Milestone
  • Auto-Complete Case Milestones
  • Where to View Milestones
  • Milestone Statuses
  • Milestone Actions
  • Recurrence Types
  • Objects with Milestones
  • Milestone Behaviors
  • Create a Process
  • Customize Fields
  • Add a Milestone
  • Add a Milestone Action
  • Apply a Process to an Entitlement
  • How Records Move Through Processes
  • How Business Hours Work
  • Updating Entitlement Processes
  • Creating New Versions
  • Using New Versions
  • Set Up Service Contracts
  • Add Contract Line Items
  • Service Contract Fields
  • Contract Line Item Fields
  • Entitlements in Experience Cloud Sites
  • Configure Settings
  • Create Assets
  • Considerations
  • Hierarchical
  • Replacements
  • Asset Fields
  • Add Contact Requests to Experience Cloud Sites
  • Contact Request Considerations
  • Edit Profile Access to My Service Journey
  • Service Cloud Mobile Access
  • Ethical Customer Service
  • Service Console
  • Design Your Quick Text Strategy
  • Enable Quick Text
  • Create Quick Text
  • Share Using a Folder
  • Share a Single Quick Text
  • Insert Quick Text
  • Prerequisites
  • Irreversible Macros
  • Create a Bulk Macro
  • Tips for Creating Bulk Macros
  • Run a Bulk Macro on Multiple Records
  • Add Logic to Macros
  • Tips for Creating Macros
  • Add and Replace Case Field Values
  • Insert Quick Text in a Social Post
  • Attach a Knowledge Article to an Email
  • Run a Macro
  • Clone Macros
  • Share a Single Macro
  • Search All Text Fields in Macros
  • Lightning Experience Considerations
  • Email Publisher Actions
  • Knowledge Actions
  • Custom Quick Actions
  • Experience Cloud Site Publisher Actions
  • Social Actions
  • Keyboard Shortcuts
  • Create a Flow to Link Voice Callers to Records
  • Create a Flow to Link Contacts to Cases
  • Create a Flow to Link Individuals to Messaging Sessions
  • Create Channel-Object Linking Rules with a Guided Setup Flow (Beta)
  • Add Channel-Object Linking Rules for Voice Calls (Beta)
  • Agent Experience for Channel-Object Linking (Beta)
  • Automatically Trigger an Action Based on Detected Keywords
  • Verify That Contact Lens Is Enabled
  • Verify That Contact Lens Speech Analytics Is Enabled
  • Update Your Contact Center
  • Create a Rule in Amazon Connect That Identifies Intelligence Signals
  • Enable Conversation Intelligence in Amazon Connect to Process the...
  • Prepare Conversation Intelligence for Partner System Intelligence...
  • Create a Conversation Intelligence Rule to Trigger an Action
  • Create a Custom Component to Trigger an Action
  • Create the Recommendations
  • Create the Recommendation Strategy Flow for Next Best Action
  • Pass the Rule Name as Input to a Flow
  • Add the Einstein Next Best Action Component to the Voice Call Record...
  • Set Up an Autolaunched Flow
  • Set Up Permissions
  • Set Up Console
  • Swarm with Actions & Recommendations
  • Swarm with Quick Actions
  • Swarm with Dynamic Actions
  • Set Up Expert Finder
  • Set Up Collaboration Tool
  • Swarm in Lightning Experience
  • Swarm in Slack
  • Add Members to Swarm
  • Close a Swarm
  • Reopen a Swarm
  • Take Action in Slack
  • Swarming Considerations
  • Create a Swarm Report
  • Change Slack Channel Name
  • Customer Service Incident Management Objects and Fields
  • Cases and Incidents
  • Example of an Incident
  • Enable Customer Service Incident Management
  • Customer Service Incident Management Sample Flows
  • Considerations for Customer Service Incident Management Flows
  • Set Up Customer Service Incident Management Flows
  • Set Up Integrations
  • Add Related Issues to Case Record
  • Report On Customer Service Incident Management
  • Create an Incident
  • Identify Incident-Related Issues
  • Start a Swarm
  • Create an Incident Channel
  • Set Up an Incident Presence Status
  • Create an Incident Queue
  • Create an Incident Skill for Skill-Based Routing
  • Set Up Routing Configuration for Incidents
  • Set Up an Entitlement Process for Incidents
  • Add Entitlements to Your Page Layouts
  • Add the Milestones Component to the Incident Page Layout
  • Create an Entitlement for Incidents
  • Manage Incident SLAs with Entitlements and Milestones
  • Create a Problem
  • Identify Problem-Related Issues
  • Enable Broadcast Site Banners
  • Create Broadcast Topic
  • Assign Broadcast Topic to Network
  • Add Site Banner Component
  • Enable Broadcast Emails
  • Enable Broadcast Alerts
  • Add Incident Alerts Utility
  • Customize the Incident Alerts All Tab
  • Assign Broadcast Topic to Group
  • Enable Broadcast Slack Messages
  • Create a Broadcast Topic for Broadcast Slack Messages
  • Assign a Broadcast Topic to a Slack Channel
  • Create a Custom Broadcast Slack Message Template
  • Give Users Access to Broadcast Communications
  • Add Broadcast Communications to Incident
  • Considerations for Broadcast Communications
  • Send a Broadcast Alert
  • Respond to a Broadcast Alert
  • Send a Broadcast Slack Message
  • Update a Broadcast Slack Message
  • Delete a Broadcast Slack Message
  • Send a Broadcast Email
  • Add a Broadcast Site Banner
  • Deactivate a Broadcast Site Banner
  • Create a Change Request
  • Create a Work Plan Template
  • Create a Work Plan
  • Identify Change Request-Related Issues
  • Industries Service Innovations
  • Knowledge Help and Resources
  • Compare Lightning and Classic Knowledge
  • Mobile Limitations
  • Plan Your Knowledge Base in Lightning Experience
  • Unified Knowledge Limitations
  • Ingest Large File Content into Data Cloud
  • Lightning Knowledge Limitations
  • Considerations and Limitations for the Lightning Editor
  • Considerations and Limitations for Article Personalization for...
  • Lightning Article Editor
  • Article Personalization for Knowledge
  • Configure Knowledge Record Pages with Dynamic Forms
  • What’s Next?
  • Lightning Knowledge Migration Tool Features and Considerations
  • Plan and Sandbox Test Your Migration
  • Activation Stage
  • Validation Stage
  • Migrate a Single Article Type
  • Post-Migration Checklist
  • Enable Lightning Knowledge
  • Lightning Knowledge User Access
  • Lightning Knowledge Home and Record Pages
  • Record Type Considerations
  • Page Layout Considerations
  • Plan Your Knowledge Base in Salesforce Classic
  • Create Article Types
  • Article Type Page Layouts
  • Add Custom Fields to Article Types
  • Article Type Templates
  • Delete an Article Type
  • Create Public Groups for Knowledge
  • Assign Article Actions to Public Groups
  • Enable Knowledge One with Permission Sets
  • Enable Knowledge One with Profiles
  • Compare Article Widgets for Cases at a Glance
  • Articles or Knowledge Tab
  • Example Apex for Submitting Articles from Cases
  • Use Videos from Any Provider with a Custom Visualforce Page
  • Knowledge Settings
  • Knowledge Scalability
  • Control Data Integrity with Validation Rules
  • Define Validation Status Picklist Values
  • Modify Default Category Group Assignments for Articles
  • Filter Articles with Data Category Mapping
  • Create Workflow Actions for Knowledge
  • Custom Fields for Articles
  • Field-Level Security on Articles
  • Article History Tracking (Lightning Experience)
  • Article History Tracking (Salesforce Classic)
  • Set Up Actions to Insert Articles to Channels (Lightning)
  • Set Up Actions to Insert Articles to Case Publishers (Classic)
  • Set Up Actions to Share Article URLs in Channels and Case Publishers
  • Add Knowledge Pages to Enhanced LWR Sites
  • Add the Knowledge Article Component to Enhanced LWR Knowledge Pages
  • Create a .csv File for Article Import
  • Set Article Import Parameters
  • Create an Article .zip File for Import
  • Article and Translation Import and Export Status
  • Search Highlights and Snippets
  • Create Synonym Groups
  • Promote Articles in Search Results
  • Manage Promoted Search Terms
  • Enable Topics for Articles
  • Article Search Results
  • Use More Case Keywords to Find Articles
  • Search for Articles in Lightning Experience
  • Search for Articles in Salesforce Classic
  • List View Considerations for Lightning Knowledge
  • Guidelines for Using the Lightning Knowledge Component
  • Share Article URLs in Channels
  • Share Articles in Channels in Lightning Knowledge
  • Share Article Contents in Case Publishers in Salesforce Classic
  • When Are Lightning Authoring Actions Available?
  • Create and Edit Articles
  • Publish Articles and Translations
  • Translate Articles in Lightning Knowledge
  • Translate Articles in Salesforce Classic
  • Archive Articles and Translations
  • Delete Articles and Translations
  • Compare Versions of an Article
  • Rich Text Fields in Knowledge Articles
  • Create and Link to Anchors
  • Target Behavior for Smart Links
  • Smart Link Considerations
  • Create Persistent Links to Lightning Knowledge Articles
  • Create Smart Links with the Link Tool in Salesforce Classic
  • Salesforce Knowledge Article Versions
  • Support a Multilingual Knowledge Base
  • Export Articles for Translation
  • Import Translated Articles
  • Set Up Primary Article and Translation Side-By-Side View
  • Keyboard Shortcuts for Data Categories
  • Create and Modify Category Groups
  • Delete and Undelete Category Groups
  • Add Data Categories to Category Groups
  • Modify and Arrange Data Categories
  • Delete a Data Category
  • Activate Data Categories on Your LWR Site
  • Add the Network Data Category Object Page (Beta)
  • Manage Data Categories on Your LWR Site
  • How Category Visibility Differs from Other Salesforce Models
  • Category Group Visibility on Roles
  • Modify Default Data Category Visibility
  • Edit Category Group Visibility
  • Category Group Article Visibility Settings Examples
  • Choose the Sharing or Access Model for Lightning Knowledge
  • Sharing Considerations for Lightning Knowledge
  • Service Catalog Permissions
  • Catalog Fulfillments
  • Create a Catalog Fulfillment
  • Create a Data Category Group
  • Create a Catalog Category
  • Create a Catalog Item
  • Create Eligibility Rules for Catalog Items
  • Use Actions & Recommendations to Run Catalog Items
  • Retrieve Catalog Item Metadata
  • Catalog Requests
  • Setting Up Your Service Catalog Site
  • Service Catalog Site Glossary
  • Service Catalog Site Resource Hub
  • Service Catalog Site Basics
  • Determining Your Setup Pathway
  • Set the Service Catalog Site Setup Configurations
  • Service Catalog Site Permissions Assignments
  • Set Up Service Catalog Guest Users
  • Verify the Service Catalog Pages Installation
  • Configure the Home Page
  • Configure the Search Page
  • Set Up the Service Catalog Pages
  • Set Up the Service Catalog Request Page
  • Set Up Your Site Navigation Menu
  • Configure Aura Guest User Access
  • LWR Service Catalog Site Guidelines
  • Add Data Categories to Your Site
  • Set Up the Home Page
  • Set Up the Search Page
  • Set Up the Service Catalog Site Pages
  • Change the Data Category Path Shown in Your Site
  • Step I: Create a Visualforce Page
  • Step II: Create a Salesforce Site
  • Step I: Customize Your Site
  • Step II: Set Your Site Administration Settings
  • Step III: Take Your Site Live
  • Service Catalog in Einstein Copilot (Beta)
  • How Service Catalog Works in Einstein Copilot (Beta)
  • Copilot Action: Update Email Address (Beta)
  • Copilot Action: Update Phone Number (Beta)
  • Copilot Action: Get Help (Beta)
  • Build Service Catalog Actions (Beta)
  • Guided Setup Flow
  • Experience Cloud Sites
  • Create Service Cloud Channels
  • Understand the Details of the Routing Lifecycle
  • Prepare to Route to Queues
  • How Does Skills-Based Routing Work?
  • How Does Skills-Based Routing Differ from Queue-Based Routing?
  • Prepare to Route to Skills
  • Skills-Based Routing Limitations
  • Prepare to Route to Agents
  • Route to a Bot
  • Route Chats to a Queue
  • Route Calls to a Queue
  • Route Messages to a Queue
  • How Does an Omni-Channel Flow Work?
  • Create the recordId
  • Create the skillList
  • Create the prechat
  • Create the input_record
  • Create the reasonForNotRouting
  • Using Multiple Add Screen Pop Actions in an Omni-Channel Flow
  • Store Screen Pop Instructions in a Variable
  • Make Smarter Routing Decisions by Checking Agent Availability
  • Route Work Items to Queues
  • Prerequisites to Route Work to Skills
  • Add a Skill Requirement Action
  • Add a Route Work Action
  • Route Work Items Directly to a Specific Agent
  • Route Work Items to an Enhanced Bot
  • Create Cases for Inbound Calls with an Omni-Channel Flow Template
  • Assign an Omni-Channel Flow to a Chat Button
  • Assign an Omni-Channel Flow to a Phone Channel
  • Assign an Omni-Channel Flow to Route Cases from Email-to-Case
  • Invoke an Omni-Channel Flow to Route Non-Real-Time Objects
  • Considerations When Using Omni-Channel Flows
  • Enable Skills-Based Routing Rules from the Routing Configuration
  • Map Work-Item Field Values to Skills
  • Routing Salesforce and Partner Channels
  • External Routing
  • Prioritize with Interruptible Capacity
  • Routing Work When the Omni-Channel Routing Service Is Unavailable
  • Comparison of Standard and Enhanced Omni-Channel
  • Enable and Configure Omni-Channel
  • Set Up Secondary Routing Priority
  • Understand Capacity Models
  • Set Up a Status-Based Capacity Model
  • Configure Work Items as Primary or Interruptible
  • Configure After Conversation Work Time
  • Service Channel Settings
  • Supported Objects for Omni-Channel
  • Add the Omni-Channel Component to a Lightning App
  • Add the Omni-Channel Component to the Classic Console
  • Control Visible Work Item Details in Omni-Channel with Compact Layouts
  • How Does Omni Mobile Work?
  • Enable Omni Mobile for Agents
  • Limitations for Omni Mobile
  • Enable Omni Supervisor
  • Enable Supervisors to Change Agent Queues and Skills
  • Show the Default Actions on Omni Supervisor Tabs
  • Create the Screen Flow for the Omni Supervisor Custom Action
  • Add the Custom Action to Omni Supervisor Tabs
  • Change What Supervisors See in Omni Supervisor
  • Create Custom Tabs for Omni Supervisor
  • Show All Offline Agents in Omni Supervisor
  • Add Omni Supervisor to a Lightning App
  • Add Omni Supervisor to the Classic Console
  • Create Presence Statuses
  • Set Access to Presence Statuses
  • Create Presence Configurations
  • Set Up Agents’ Capacities
  • Create Service Resources for Agents
  • Create Queues
  • Routing Configuration Settings
  • Omni-Channel Routing Model Options
  • Associate Routing Configurations and Agents with Queues
  • Create a Custom Report Type for Queue Members
  • Report on Queue Membership
  • Create Custom Report Types for Omni-Channel
  • Access Omni-Channel Setup Home
  • Test Your Omni-Channel Implementation
  • Agents Tab Fields
  • How After Conversation Work Affects Agent Capacity
  • Queues Backlog Tab Fields
  • Assigned Work Tab Fields
  • Skills Backlog Tab Fields
  • Wallboard Tab Fields
  • Sort and Filter in Omni Supervisor
  • Change Queues and Skills Assigned to Agents
  • Support and Train Your Agents
  • Transfer a Work Item to a Different Skill Set
  • Use the Omni-Channel Component to Work with Customers
  • Get Help from a Supervisor
  • Set Up Omni-Channel on Your Mobile Device
  • Manage Work with Omni Inbox

Assignment Rules

  • View and Edit Assignment Rules
  • Differences Between Auto-Response Rules and Workflow Email Alerts
  • Escalation Rule Entries
  • Escalation Actions
  • When do rules execute?
  • Limits for Assignment, Auto-Response, and Escalation Rules
  • Einstein Case Routing
  • Build AI Solutions with Agents and Einstein
  • Service Cloud Billable Usage Types
  • Service and Data Cloud
  • Service Intelligence Considerations and Requirements
  • Create a Data Cloud Salesforce CRM Connection
  • Enable Service Cloud Features
  • Update the Data Cloud Salesforce Connector Permission Set
  • Install the Service Data Kit
  • Set Up Service Data in Data Cloud
  • Deploy the Einstein Conversation Mining Insights Data Stream
  • Deploy the Knowledge Article Views Data Stream
  • Enable CRM Analytics for Service Intelligence
  • Install the Knowledge Flow for Service Intelligence
  • Install Service Intelligence
  • Monitor, Update, and Delete Service Intelligence Apps
  • Delete Service Intelligence Apps
  • Service Intelligence Data Refresh
  • Enable the Propensity to Escalate Insight Component
  • Use the Propensity to Escalate Insight Component
  • Use the Customer Effort Score Insight Component
  • Use the Time to Resolve Insight Component
  • Service Intelligence Cases Dashboard
  • Service Intelligence Einstein Case Management Dashboard (Beta)
  • Service Intelligence Omni-Channel Dashboard
  • Service Intelligence Einstein Conversation Mining Dashboard
  • Service Intelligence Agent Performance Dashboard
  • Service Intelligence My Performance Dashboard for Agents
  • Service Intelligence Knowledge Articles Dashboard
  • Explore Service Intelligence Data in Tableau
  • Analyze Conversation Transcript Data in Data Cloud
  • Export Conversation Transcripts
  • Block Sensitive Data in Messaging Sessions and Voice Call Transcripts
  • Create and Assign Skills
  • Create a Scheduling Rule
  • Create a Scheduling Constraint
  • Create a Scheduling Objective
  • Create Shift Templates
  • Create Shifts from a Capacity Plan
  • Non-Standard Shifts
  • Create a Shift Segment Type
  • Update a Shift Segment
  • Mass Shift Update
  • Batch Assign
  • Get Candidates
  • Troubleshooting Shift Scheduling
  • Managing and Viewing Shift Schedules
  • Preparing to Use Service Resource Preferences
  • Set a Work Preference
  • Preparing for Time Sheets and Resource Absences
  • Approve Time Sheets and Time-Off Requests
  • Submit Your Time Sheet
  • Submit Time Off with Resource Absences
  • Feedback Management
  • Case Escalation Rule Queue
  • Entitlement Process Queue
  • Article Process Actions
  • Use Custom Report Types
  • Support Reporting Tips
  • Employee Service Data Model
  • Enable Integration with Workday
  • View Employee Records Imported from Workday
  • Provision Users with Required Profiles and Auto-Create User Records
  • Configure the Reports To Field on Person Account
  • Review and Assign Employee Hub Permissions
  • Employee Hub Site Creation
  • Configure the Employee Details Component
  • Configure the Employee Hub Service Catalog Component
  • Configure the Tile Menu Component
  • Salesforce Knowledge Enablement
  • Email-to-Case Setup
  • Web-to-Case Setup
  • Update Messaging Session with Employee Details
  • Set Up Case Management Bot
  • Create a Flow by Using the Identify Manager Template
  • Create an Orchestration by Using the Approve Case Request Template
  • Limitations of Advanced Approvals in Employee Service
  • Notifications Setup
  • Review and Assign HR Service Workspace Permissions
  • Configure Dashboard and Reports
  • Configure Employee Profile Card Component
  • Provide Access to Account, Contact, and Employee Objects
  • Set Up Person Account Page
  • Configure Field-Level Security of Employee2 Fields
  • Modify the Create Employee Flow
  • Modify the Update Employee Flow
  • Set Up Knowledge
  • Set Up Voice Calls
  • Employee Hub Features
  • Manage Your Profile Details
  • Refer to Knowledge Articles to Resolve Issues
  • Raise Service Requests
  • Manage Cases
  • Manage Approvals
  • HR Service Workspace Features
  • Manage Employees
  • Interact with Employees
  • Deliver Field Service

You are here:

  • Salesforce Help
  • Service Cloud

Assignment rules automate your organization’s lead generation and support processes. Use lead assignment rules to specify how leads are assigned to users or queues. Use case assignment rules to determine how cases are assigned to users or put into queues.

Required Editions

Lead assignment rules can assign leads regardless of whether leads are created manually, are generated from Web-to-Lead forms, or are imported using the Data Import Wizard.

Case assignment rules can assign cases regardless of how cases are created. Cases can be created manually or automatically using Web-to-Case, Email-to-Case, On-Demand Email-to-Case, the Self-Service portal, the Customer Portal, Outlook, or Lotus Notes.

Organizations typically use one rule for each overall purpose. For example, use one lead assignment rule for importing leads and use a different lead assignment rule for web-generated leads. Or use one case assignment rule for standard use and one case assignment rule for holiday use. For each rule type, only one rule can be in effect at any time.

Each rule consists of multiple rule entries that specify exactly how the leads or cases are assigned. For example, your standard case assignment rule can have two entries: cases with “Type equals Gold” are assigned to the “Gold Service” queue, and cases with “Type equals Silver” are assigned to the “Silver Service” queue.

To create an assignment rule, from Setup, enter Assignment Rules in the Quick Find box, then select Lead Assignment Rules or Case Assignment Rules .

Sample Assignment Rule

The following case assignment rule assigns a case to a specific queue based on the account rating:

Rule Name — Hot Account Assignment

Rule Entries:

  • Set Up Assignment Rules

Company Logo

Cookie Consent Manager

General information, required cookies, functional cookies, advertising cookies.

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings. Privacy Statement

Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.

Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.

Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.

Cookie List

lead assignment using apex

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

Salesforce Lead assignment rules ensure Leads are assigned to the appropriate user or queue for follow up. They also liberate marketers from trying to maintain sales territory logic within their Marketing Automation Platform (MAP).

>> Related: How to Build a SLA Alert in Salesforce <<

When a new Lead is created, Salesforce will use 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 ?

In this post:

Re-running Lead Assignments for just a few Leads

If you only need to do this for a single Lead record, the solution is simple.  Edit the record and select the optional “ Assign using active assignment rule “ checkbox.

Edit Lead Screenshot with Assign box checked

If you need to do a one-time batch reassignment of a number of records, export the relevant Lead Ids.  Then 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

But you may want to automatically re-run Salesforce Lead Assignments

But you may 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.

To do this, we combine Flow and an Apex Invocable method. We 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 Flow. The method accepts a single parameter (a list of the Lead Ids to be assigned) that you’ll pass into the method from your Flow.

That’s it. Just those four lines are all you need in your code. The logic for firing the assignment rules will be configured in one or more Flows.

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

Work with a developer to ensure you’re accounting for any requirements specific to your Salesforce instance.

Using Salesforce Flows for Lead Assignment Rules

Now we’ll create our declarative logic of when to fire the code, using a Flow.

1) Create a new Flow by searching for Flows under Setup and clicking the New Flow button in the top right. This example is for a Record-Triggered Flow , but you can design it a number of ways.

lead assignment using apex

2) Select the Lead object for your Flow and configure the trigger for when a record is created or edited .

lead assignment using apex

3) Then set the Entry Conditions.  In this use case, we want to re-assign Leads after they meet a certain Lead Score. Select “custom condition logic is met. ” Set the condition that the Lead Score is greater than or equal to 100.

Under the “When to Run the Flow for Updated Records” section, select the option to only execute when a record is updated to meet the condition requirements . This means we’ll only execute the actions if the record previously did not meet the criteria, but now does after being updated.

lead assignment using apex

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 path to call our Apex method.

lead assignment using apex

In this case, we want the logic to execute ASAP, so we’ll set the schedule for 0 minutes from now.

lead assignment using apex

5) Once saved, we can create a new action. Click to Add a New Element , and select an Action type. 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.

lead assignment using apex

6) After saving, your Flow looks like this:

lead assignment using apex

Activate your flow, test in your sandbox, and deploy 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, it’s usually <2 minutes, but you can monitor this under Setup > Flows and viewing the Paused and Waiting Interviews section.

Scheduled Action Monitoring

The nice part about this 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 Flow (Step 3) without having to touch any code.

lead assignment using apex

You might also like

lead assignment using apex

Sales Funnel ROI Calculator

lead assignment using apex

8 Lead Management Process Samples

lead assignment using apex

How to Measure Lead Follow-Up Beyond First Touch

Get our newsletter.

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

  • Name * First Last

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.

  • Full Name *
  • Job Title *
  • What systems and challenges do you have?* *
  • Hidden utm_medium
  • Hidden utm_source
  • Hidden utm_campaign
  • Hidden utm_content
  • Hidden utm_term

Download Resource

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

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.

lead assignment using apex

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

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

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

Salesforce <3 Codespace

A few weeks ago, Microsoft held Build 2020, the developer focused conference, where they announced Codespace. Codespace basically allows...

Comentários

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.

IMAGES

  1. How to Re-run Salesforce Lead Assignment Rules: Flows & Apex

    lead assignment using apex

  2. Salesforce Lead Assignment rules

    lead assignment using apex

  3. How to Automate Lead Assignment for Salesforce Platforms

    lead assignment using apex

  4. How to Create Lead Assignment Rules in Salesforce?

    lead assignment using apex

  5. How to convert lead using apex in salesforce?

    lead assignment using apex

  6. Enable Lead Assignment Rules from Apex Code

    lead assignment using apex

VIDEO

  1. 00077-Oracle Fusion REST Accesing Using APEX 0003

  2. 00075 0001 Oracle Fusion REST Accesing Using APEX0001

  3. Why Apex Legends Pros Are Using The Mozambique #shorts

  4. 00078 0004 Oracle Fusoin REST Accesing Using APEX0004

  5. Using Apex Legends to Improve at Basketball 🏀🔥 #apexlegends #titanfall2 #tf2 #basketball

  6. Apex Legends_Follow my lead to Victoria

COMMENTS

  1. DmlOptions.AssignmentRuleHeader Class | Apex Reference Guide ...

    Enables setting assignment rule options. The following are properties for DmlOptions.AssignmentRuleHeader. Specifies the ID of a specific assignment rule to run for the case or lead. The assignment rule can be active or inactive. If specified as true for a case or lead, the system uses the default (active) assignment rule for the case or lead.

  2. leads - Creating Assignment rules via APEX Code - Salesforce ...

    Is there any way possible that I can create a new assignment rule on lead via Apex code. If possible can someone help me with the code snippet for the same. Also is it possible to transfer assigment rule via Unmanaged Package from one org to another?

  3. Running Lead Assignment Rules From Salesforce Flow

    There are 4 steps to solve Pamela’s business requirement using Salesforce Flow and Apex. We must: Setup a lead assignment rule; Create Apex class & Test class; Salesforce before save flow. Define flow properties for record-triggered flow; Add a decision element to check the lead source; Add an assignment element to update status & rating

  4. apex - How do I run the default Lead assignment rules on a ...

    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.

  5. Create a Round Robin Lead Assignment Rule - Salesforce

    You can set up round robin lead assignment with a few custom fields and a lead assignment rule. Create a Lead Number f+Field Creating a Lead Number f+Field gives each new lead a unique ID.

  6. Assignment Rules - Salesforce

    Assignment rules automate your organization’s lead generation and support processes. Use lead assignment rules to specify how leads are assigned to users or queues. Use case assignment rules to determine how cases are assigned to users or put into queues.

  7. How to Re-run Salesforce Lead Assignment Rules: Flows & Apex

    This tutorial walks Salesforce Admins step-by-step through the process to re-run Salesforce Lead Assignment rules using Flow and Apex.

  8. How to run Lead Assignment Rule using Apex on ... - Medium

    Recently, I had requirement where the lead assignment rule needs to be run on existing Lead records on passing some filter criteria. If you are using the below code on After Update logic then...

  9. Apex: Assign owner using Lead Assignment Rules - Marc The Code

    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.

  10. Setting Lead Assignment Rules with Apex | Soliant Consulting

    Don't overlook Assignment Rules with Apex when creating a new lead via Visualforce or web form. Find our solution and code example here.