I have created a trigger to update a custom date/time field (called First_Aircall_Logged__c). Basically when an (Aircall) task is created on a Case; The trigger updates the Case field First_Aircall_Logged__c with the Task field CreatedDate.
The trigger is working fine but I don't think I wrote it the best way possible. What I really wanted to do was to get tasks where WhatId = CaseId. I am not doing exactly that even though my trigger is working.
How can I optimize my trigger? What would be the best way to write a trigger to update a field of a related object. Thanks
trigger AircallTaskTrigger on Task (after insert, after update) {
//First part of the code: How to query to match WhatId to CaseId
Set<Id> caseIds = new Set<Id>();
Map<Id, Task> aircallTask = new Map<Id, Task>([SELECT Id, WhatId FROM Task WHERE CallDisposition LIKE '%aircall%' AND Id IN: Trigger.New]);
for(Task t: aircallTask.values()) {
System.debug('##### Aircall Task ' + aircallTask);
if(t.WhatId != null ) caseIds.add(t.WhatId);
}
Map<Id, Case> caseWithAircallTask = new Map<Id, Case> ([SELECT Id, First_Aircall_Logged__c, (SELECT Id, CreatedDate FROM Tasks) FROM Case WHERE Id IN: caseIds]);
if(caseWithAircallTask.size() > 0) {
for(Case c :caseWithAircallTask.values()) {
System.debug('Cases with Aircall Task ' + caseWithAircallTask);
c.First_Aircall_Logged__c = c.tasks[0].CreatedDate;
}
}
update caseWithAircallTask.values();
}