The goal of this case trigger is to parse out a CC List text string on the case object and insert each individual string as an email on the CC_List__c object. This is working, albeit a bit too well!
Unfortunately, each time the case is saved, the CC List field on the case is duplicating records on the CC_List__c object. My goal is to have the CC List field on the case object always 1 for 1 match the values listed in the related object's CC_List__c list.
trigger CCList on Case (after insert, before update, before delete) {
class CaseTriggerUtil {
void handleCCFieldChangeEvent(Case [] argCases, Boolean argIsDelete) {
Set<ID> lDeadParentIDSet = new Set<ID>();
Set<String> lUniqueCCIDSet = new Set<String>();
List<CC_List__c> lNewCCRecords = new List<CC_List__c>();
for(Case lCase : argCases) {
if(argIsDelete) {
lDeadParentIDSet.add(lCase.id);
}
else {
if(lCase.CC_List__c == null || lCase.CC_List__c.trim() == '') {
lDeadParentIDSet.add(lCase.id);
continue;
}
List<String> lCCValues = lCase.CC_List__c.trim().split(',');
for(String lStrCC : lCCValues) {
String lStrChildRecUniqueID = lCase.id + '_' + lStrCC.trim();
lNewCCRecords.add(new CC_List__c(Related_Case__c=lCase.id, My_ID__c = lStrChildRecUniqueID, Email_Address__c = lStrCC.trim()));
lUniqueCCIDSet.add(lStrChildRecUniqueID);
}
}
}
if(!argIsDelete) {
Database.insert(lNewCCRecords, false);
}
delete [SELECT id FROM CC_List__c WHERE Related_Case__c IN:lDeadParentIDSet OR (Related_Case__c IN:argCases AND My_ID__C NOT IN:lUniqueCCIDSet)];
}
}
List<Case> lCases = (Trigger.isDelete ? Trigger.old : Trigger.new);
new CaseTriggerUtil().handleCCFieldChangeEvent(lCases, Trigger.isDelete);}
Any thoughts?
cc_list__c
. This is the easiest solution if it is not important to preserve the child createdDate or createdById