Here's the scenario:
I've a custom object (ObjectA__c) with only one custom field Email_Address__c (which can be unique).
Now I would be inserting new records using Data Loader such that: 1) If record in .csv file is already in ObjectA then, do nothing. 2) If record in .csv file and not in ObjectA then, insert into the object. 3) If record is not in .csv file and present in ObjectA then, delete the record from ObjectA.
I'm performing insert operation using data loader and written Before Insert Trigger. The problem I'm facing is: The trigger shows correct output in System.debug statements but, it doesn't delete any records. New records are inserted correctly. Records existing in both .csv file and ObjectA are left untouched. But, records present in ObjectA but missing in .csv file are not deleted. The list correctly shows the records to be deleted but somehow it seems the DML operation is not performed.
Here's the code for the trigger:
trigger ListUpload on ObjectA__c (before insert) {
//Using Flag.boolFlag to avoid execution of the trigger twice
if(Flag.boolFlag){
// newrecords set will hold all the email address of the records to be inserted through data loader
Set<String> newrecords = new Set<String>();
for(ObjectA__c ce1 : trigger.new){
newrecords.add(ce1.Email_Address__c);
}
System.debug('@@@@'+'New Records Size: '+newrecords.size());
//this condition ensures trigger will take action only if inserted using data loader
if(newrecords.size()>1){
//existingrecords list will hold all the records in the ObjectA__c
List<ObjectA__c> existingrecords = [Select Id, Email_Address__c from ObjectA__c];
system.debug('@@@@'+'Exisiting records count:' +existingrecords.size());
//create a map of existingrecords
Map<String,Id> existingrecordsmap = new Map<String,Id>();
For(ObjectA__c ce2: existingrecords){
existingrecordsmap.put(ce2.Email_Address__c, ce2.Id);
}
List<ObjectA__c> todelete = new List<ObjectA__c>();
string emailid;
//check for the condition. If record record not found in .csv file then, add it to todelete list
For(ObjectA__c ce3: existingrecords){
emailid = ce3.Email_Address__c;
if(newrecords.contains(emailid)==false){
todelete.add(ce3);
}
}
System.debug('@@@@'+'For Loop: To be deleted'+'Size'+todelete.size());
integer i;
For(i=0;i<todelete.size();i++){
System.debug('@@@@'+'Final to be deleted: '+todelete.get(i).ID+' '+todelete.get(i).Email_Address__c);
}
//delete todelete
delete todelete;
integer k;
List<ObjectA__c> FinalList = [Select Id, Email_Address__c from ObjectA__c];
System.debug('@@@@'+'No of rows after deletion: '+FinalList.size());
for(k=0;k<FinalList.size();k++){
System.debug('@@@@'+FinalList.get(k).Email_Address__c);
}
}
Flag.boolFlag=false;
}
}
Flag class code:
public class Flag {
public static boolean boolFlag = true;
}