Sub topic 12
Running assignment rules and setting queue owners from Apex
This chapter covers two ways to route a case from code. You can ask Salesforce to run the active case assignment rule, or you can set OwnerId to a queue yourself. It assumes you can read basic Apex and SOQL, and that you know how queues and assignment rules work from the earlier chapters.
Why assignment rules do not run by default
Assignment rules run automatically for cases created through Web-to-Case and Email-to-Case, and in the UI when the user ticks "Assign using active assignment rules". They do not run for DML (database operations such as insert and update) in Apex unless you ask for them. A case inserted from Apex with no OwnerId is owned by the running user, and no rule entry is evaluated.
You have two options:
- Run the rule. Pass a
Database.DMLOptionsobject with the assignment rule header set. The rule decides the owner. - Set the owner directly. Look up the queue and assign its Id to
OwnerId. Your code decides the owner.
Running the active assignment rule
Database.DMLOptions has an assignmentRuleHeader property. Setting useDefaultRule = true selects the active rule. Alternatively, set assignmentRuleId to a specific rule Id. The two settings are mutually exclusive.
Case c = new Case(
Subject = 'Cannot log in to the portal',
Origin = 'Web',
Priority = 'High'
);
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
c.setOptions(dmo);
insert c;You can also pass the options as an argument to the Database method. This form is usually better in bulk code, because one options object serves the whole list:
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
dmo.optAllOrNone = false;
List<Database.SaveResult> results = Database.insert(newCases, dmo);The same header works for updates. Calling Database.update(cases, dmo) re-evaluates the rule against the changed records. This is how you re-route a case after its Priority or Type changes.
What the rule does to the owner
- If a rule entry matches, the rule sets the owner to the entry's user or queue. This overrides any
OwnerIdyou set on the record. - If no entry matches, the case goes to the default case owner configured in Support Settings.
- If the rule entry has an email template, the new owner is notified, as in the UI.
Setting a queue owner directly
A queue is stored as a Group record with Type = 'Queue'. A case's OwnerId accepts a user Id or a queue Id, so you can assign the queue Id directly.
Group tier2 = [
SELECT Id
FROM Group
WHERE Type = 'Queue' AND DeveloperName = 'Tier2_Support'
LIMIT 1
];
Case c = new Case(
Subject = 'Data export fails',
Origin = 'Email',
OwnerId = tier2.Id
);
insert c;Use DeveloperName, not Name. The label can be edited by an admin and differs between sandboxes and translations, while the developer name stays stable when you deploy.
The queue must support Case
A queue can only own records of the object types listed in its "Supported Objects". The link is stored in QueueSobject. If the queue does not support Case, the insert fails with an invalid owner error. To make the lookup safe, join on QueueSobject:
List<QueueSobject> supported = [
SELECT QueueId
FROM QueueSobject
WHERE SobjectType = 'Case'
AND Queue.DeveloperName = 'Tier2_Support'
];An empty list means the queue is missing or does not support Case, and your code can fail with a clear message.
Choosing between the two approaches
| Question | Run the rule | Set OwnerId |
|---|---|---|
| Who decides the owner? | Admins, in rule entries | Developers, in code |
| Changing the routing | Edit the rule in Setup | Edit and deploy code |
| Matches UI and Web-to-Case behavior | Yes | No |
| Works inside a before trigger | No | Yes |
| Good for a fixed destination | Overkill | Yes |
Prefer the rule when the logic is business criteria that admins maintain, such as Priority, Origin, or Account tier. Prefer a direct assignment when the destination is fixed, such as an integration that always sends a case to one queue.
Choosing a routing path
A reusable routing class
Keeping routing in one class avoids duplicated queries and makes the behavior testable. This class does both jobs and avoids a SOQL query per record.
public with sharing class CaseRouter {
public class RoutingException extends Exception {}
public static List<Database.SaveResult> insertWithRule(List<Case> cases) {
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
dmo.optAllOrNone = false;
return Database.insert(cases, dmo);
}
public static Id queueIdFor(String developerName) {
List<QueueSobject> rows = [
SELECT QueueId
FROM QueueSobject
WHERE SobjectType = 'Case'
AND Queue.DeveloperName = :developerName
LIMIT 1
];
if (rows.isEmpty()) {
throw new RoutingException(
'No queue named ' + developerName + ' supports Case.'
);
}
return rows[0].QueueId;
}
public static void assignToQueue(List<Case> cases, String developerName) {
Id queueId = queueIdFor(developerName);
for (Case c : cases) {
c.OwnerId = queueId;
}
}
}assignToQueue only sets the field. The caller decides whether the cases are inserted, or are in a before trigger where the platform saves them.
Triggers and the limits of DMLOptions
DMLOptions applies to the DML statement you write. In a before insert trigger, the platform performs the save, so you have no statement to attach options to. For triggers, use one of these:
- In
before insert, setOwnerIddirectly withassignToQueue. This is simple and costs no extra DML. - In
after insert, query fresh copies of the records and callDatabase.update(list, dmo)to run the rule. This costs an extra DML statement and re-fires update triggers, so add a recursion guard.
trigger CaseTrigger on Case (before insert) {
List<Case> highPriority = new List<Case>();
for (Case c : Trigger.new) {
if (c.Priority == 'High' && c.Origin == 'API') {
highPriority.add(c);
}
}
if (!highPriority.isEmpty()) {
CaseRouter.assignToQueue(highPriority, 'Tier2_Support');
}
}Logic in the trigger body is kept small here for clarity. A real project would delegate to a handler class.
Testing routing code
Queues and groups are setup objects. Inserting a Group and then a Case in the same transaction raises MIXED_DML_OPERATION. The usual fix is to create the setup records inside System.runAs, using the current user.
@IsTest
private class CaseRouterTest {
@IsTest
static void assignsCaseToQueue() {
Group q = new Group(
Name = 'Tier 2 Test',
DeveloperName = 'Tier2_Test',
Type = 'Queue'
);
System.runAs(new User(Id = UserInfo.getUserId())) {
insert q;
insert new QueueSobject(QueueId = q.Id, SobjectType = 'Case');
}
Case c = new Case(Subject = 'Test', Origin = 'Email');
CaseRouter.assignToQueue(new List<Case>{ c }, 'Tier2_Test');
insert c;
Case saved = [SELECT Owner.Type FROM Case WHERE Id = :c.Id];
Assert.areEqual('Queue', saved.Owner.Type);
}
}Testing the assignment rule itself is harder. Rules are metadata, so a test sees the org's active rule, and the result depends on its entries. Tests that assert specific owners can break when an admin edits the rule. Keep rule-dependent assertions loose, such as "the owner was set", or cover rule behavior with manual testing as described in the troubleshooting chapter.
Verifying the result
After running code in a sandbox, confirm what actually happened. This query shows open cases still owned by a queue:
SELECT Id, CaseNumber, Subject, Status
FROM Case
WHERE Owner.Type = 'Queue' AND IsClosed = false
ORDER BY CreatedDate ASCCommon errors
- Case stays with the creating user. No DMLOptions were passed, or the options were set on a different record instance than the one inserted.
- Invalid owner error on insert. The queue does not list Case as a supported object, or the Id is from another org.
List has no rows for assignment. TheGroupquery found nothing because of a wrong developer name. UseQueueSobjectand check for an empty list.- Owner is not the one you set. The rule ran and overrode
OwnerId. Choose one mechanism per code path. MIXED_DML_OPERATIONin tests. Setup and non-setup inserts are in the same context. Wrap the setup inserts inSystem.runAs.- Rule runs but nothing changes. The rule has no active entry matching the record, so the case goes to the default owner.
Exercise
An integration inserts cases through Apex with Database.insert(cases). The business wants cases with Priority "High" to follow the admin-maintained assignment rule, but the cases still end up owned by the integration user. What is missing, and what changes if the code also sets OwnerId to a queue?
Show answer
The code never asks for the rule to run. Create a Database.DMLOptions object, set assignmentRuleHeader.useDefaultRule = true, and call Database.insert(cases, dmo). If the code also sets OwnerId to a queue and the rule runs, a matching rule entry overrides that value. If no entry matches, the case goes to the default case owner. Choose one mechanism per code path.
Exercise
Why does a test that inserts a queue Group and then a Case fail with MIXED_DML_OPERATION, and how do you fix it?
Show answer
Group and QueueSobject are setup objects, and Case is not. Salesforce does not allow both kinds of DML in one transaction. Insert the Group and QueueSobject inside a System.runAs(new User(Id = UserInfo.getUserId())) block, which gives them a separate context, and insert the case outside it.