Bypass Assignment Rules in Apex

In Salesforce, Assignment Rules play a crucial role in automating assigning records such as Cases and leads to the right users or queues. However, there are scenarios where developers need to bypass assignment rules in Apex, especially during data migration, integrations, or custom automation while inserting case or lead record using Apex.

If you’ve ever wondered why your OwnerId keeps changing though, you set it explicitly this one is for you.

How Assignment Rule Works?

In this blog, we will work with case object. When a case is inserted

  • Salesforce checks if there is an active assignment rule
  • If found, it evaluates the rule entries
  • Ownership is automatically reassigned based on matching criteria
  • If no rule evaluates to true then, owner assigned as default owner mentioned in Setup >> Service >> Support Settings
Default Case Owner if Assignment Rule entries evaluate as false

This happens even if you set OwnerId explicitly.

How to Bypass Assignment Rules in Apex?

Salesforce provides Database.DMLOptions class to control assignment rule behavior. You need to set assignmentRuleHeader.useDefaultRule property as false. This property tells Salesforce not to apply the active assignment rules. Owner will be unchanged.

Case c = new Case(Origin = 'Email', Priority = 'Low', Status = 'New',
                  OwnerId = UserInfor.getUserId(), Subject = 'User locked out'    
         );
Database.DMLOptions dml = new Database.DMLOptions();
dml.assignmentRuleHeader.useDefaultRule = false;

c.setOptions(dml);
insert c;

Please note you can also use Database methods for ex. Database.insert(c, dml);

How to Bypass Assignment Rules in Apex REST class?

assignmentRuleHeader.useDefaultRule = false; does not work in Apex REST class. In that scenario, pass Sforce-Auto-Assign as FALSE in header at time of sending request. If header is not provided in the request, then default value is true, and this somehow overrides your useDefaultRule = false property in Apex REST class. You can also pass valid AssignmentRule Id in header to specify which Assignment Rule should trigger for routing purpose.

How to apply a specific Assignment Rule?

In some scenarios, you may want to apply a particular assignment rule, instead of default one.

Case c = new Case(Origin = 'Email', Priority = 'Low', Status = 'New',
                  OwnerId = UserInfor.getUserId(), Subject = 'User locked out'    
         );

List<AssignmentRule> asrList = [SELECT Id FROM AssignmentRule LIMIT 1];

if(!asrList.isEmpty() && asrList.size() > 0){
   Database.DMLOptions dml = new Database.DMLOptions();
   dml.assignmentRuleHeader.assignmentRuleId = asrList[0].Id;
   c.setOptions(dml);
}
insert c;

If you’re working on integrations or automation heavy Salesforce orgs mastering this concept can save hours of debugging.

You may also like...

Leave a Reply

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