When a Case is created with Origin = 'Email' and Priority = 'High', automatically assign it to a specific SLA Queue and create an Entitlement task.
Answer
Use before insert to set the owner to a Queue and after insert to create the Task. Query the Queue once.
apex
trigger CaseTrigger on Case (before insert, after insert) {
if (Trigger.isBefore) {
Id qId = [SELECT Id FROM Group WHERE Type = 'Queue' AND DeveloperName = 'High_Priority_SLA' LIMIT 1].Id;
for (Case c : Trigger.new) if (c.Origin == 'Email' && c.Priority == 'High') c.OwnerId = qId;
} else {
List<Task> tasks = new List<Task>();
for (Case c : Trigger.new) {
if (c.Origin == 'Email' && c.Priority == 'High') {
tasks.add(new Task(Subject = 'Review Entitlement / SLA', WhatId = c.Id, ActivityDate = Date.today().addDays(1)));
}
}
insert tasks;
}
}
Case Assignment Rules or Flow can also route to queues declaratively.
apex-triggertriggercodingscenariocase