I have a requirement where we will be using dataloader to upsert a number of records, and do not want to import records with matching Case_Id__c. I will be handling the update through flows since I am a novice at best at Apex. What I believe the code should be doing is creating a list of the records being imported, comparing to what we have in the database for duplicate Case_ID__c, then removing those Case_ID__c from the list before the insert. I believe there is something I'm missing at the getting existing Case_ID__c portion, but your support is appreciated and codes below:
trigger checkDuplicateCareMetxDataTrigger on CareMetx_Data__c (before insert) {
// get triggering CMX data case IDs
Set <String> CMXcaseID = new Set<String>();
for(CareMetx_Data__c newCMXData:Trigger.new){
CMXcaseID.add(newCMXData.Case_ID__c);
}
// get existing CMX data case IDs
List<CareMetx_Data__c> caseIDs = [SELECT Case_ID__c FROM CareMetx_Data__c WHERE Case_ID__c =: CMXcaseID];
Set<String> existingCaseIDs = new Set<String>();
for(CareMetx_Data__c c: caseIDs){
existingCaseIDs.add(c.Case_ID__c);
}
System.debug('Existing case IDs: ' + existingCaseIDs);
// get existing CMX data case IDs from triggering records and remove
for(CareMetx_Data__c insertCMXcaseID: [SELECT Case_ID__c FROM CareMetx_Data__c WHERE Case_ID__c !=: existingCaseIDs]){
CMXcaseID.remove(insertCMXcaseID.Case_ID__c);
}
System.debug('Case ID before trigger: ' + CMXcaseID);
}
@isTest
public class duplicateCareMetxDataTest {
static testMethod void validatecheckDuplicateCareMetxData() {
// **NEW CODE BLOCK INSERTS NEW CAREMETX RECORD**
CareMetx_Data__c newCMX = new CareMetx_Data__c(Case_ID__c = '0000000');
System.debug('Case ID before insert: ' + newCMX.Case_ID__c);
// insert CareMetx data
insert newCMX;
// retrieve the new CareMetx data
newCMX = [SELECT Case_ID__c FROM CareMetx_Data__c WHERE Id =:newCMX.Id];
System.debug('CareMetx case ID after trigger fired: ' + newCMX.Case_ID__c);
// **NEW CODE BLOCK INSERTS EXISTING CAREMETX RECORD**
CareMetx_Data__c existCMX = new CareMetx_Data__c(Case_ID__c = '6279270');
System.debug('Case ID before insert: ' + existCMX.Case_ID__c);
// insert CareMetx data
insert existCMX;
// retrieve the new CareMetx data
existCMX = [SELECT Case_ID__c FROM CareMetx_Data__c WHERE Id =:existCMX.Id];
System.debug('CareMetx case ID after trigger fired: ' + existCMX.Case_ID__c);
// **NEW CODE BLOCK UPDATES EXISTING CAREMETX RECORD**
CareMetx_Data__c upCMX = new CareMetx_Data__c(Case_ID__c = '6279270');
System.debug('Case ID before update: ' + upCMX.Case_ID__c);
// insert CareMetx data
insert upCMX;
// retrieve the new CareMetx data
upCMX = [SELECT Case_ID__c FROM CareMetx_Data__c WHERE Id =:upCMX.Id];
System.debug('CareMetx case ID after trigger fired: ' + upCMX.Case_ID__c);
// update CareMetx data
update upCMX;
}
}