Auto-Assign Case Owners by Origin in Salesforce using Apex
Automatically assigning the right owner to new Cases in Salesforce can significantly improve your support team’s efficiency. In this guide, we’ll show you how to assign Case owners dynamically based on the Origin field using Apex.
Business Requirement
Assign Case ownership based on the Origin:
- Phone → Assign to Phone Support Agent (User ID:
005XXXXXXXXXXXX
) - Email → Assign to Email Support Agent (User ID:
005YYYYYYYYYYYY
) - Web → Assign to Web Support Agent (User ID:
005ZZZZZZZZZZZZ
)
Apex Class
This Apex class handles the owner assignment logic based on the case’s Origin:
public class CaseOwnerAssigner {
public static void assignCaseOwner(Id caseId) {
Case c = [SELECT Id, Origin, OwnerId FROM Case WHERE Id = :caseId];
String phoneAgentId = '005XXXXXXXXXXXX';
String emailAgentId = '005YYYYYYYYYYYY';
String webAgentId = '005ZZZZZZZZZZZZ';
if (c.Origin == 'Phone') {
c.OwnerId = phoneAgentId;
} else if (c.Origin == 'Email') {
c.OwnerId = emailAgentId;
} else if (c.Origin == 'Web') {
c.OwnerId = webAgentId;
}
update c;
}
}
How It Works
- Query the Case record using the provided ID.
- Check the
Origin
field value. - Assign the corresponding
OwnerId
(User or Queue). - Update the Case record.
Notes
- Replace sample IDs with actual User or Queue IDs from your org.
- You can assign to Queues too—Queue IDs work in the
OwnerId
field. - To find a User/Queue ID: Open the record in Salesforce and copy the 15- or 18-digit ID from the URL.