function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shyamala VaradharajanShyamala Varadharajan 

Update Existing Record before Inserting new record to avoid Duplicates

Hello,

I have a Custom Object with 4 fields  and 1 Date Field. If I try to create a new record with same values  I need to check the old records and if the record persists then need to update the old Record with new Date . How can we achieve this. Please help
AnkaiahAnkaiah (Salesforce Developers) 
Hi Shyamala,

4 fields values should match old record?
Shyamala VaradharajanShyamala Varadharajan
Hi Ankiah,

Yes 4 field values should match old record value..This is the code I have tried but the issue is it's updating old record as well as creating new record with same values which cause duplicates.

public class duplicateHandler {
 
   public static void triggertocheckDuplicateBeforeInsert(list(List<CustObject> custList){
 Set <String> agencySet = new Set<String>();
Set <String> agencyTypeSet = new Set<String>();
Set <String> advetiserSet = new Set<String>();
Set <String> platformSet = new Set<String>();
Set <Date> startDateSet = new Set<Date>();
 
List<CustObject> oldList = new List<CustObject>();
 
        for (CustObject custMap : custList){
             agencySet.add(custMap.Agency__c);
             agencyTypeSet.add(custMap.Agency_Type__c);
             advetiserSet.add(custMap.Advertiser__c);
             platformSet.add(custMap.Platform__c);
        }
 
        List<CustObject> oldcustList = [SELECT Agency__c,Agency_Type__c,Advertiser__c,Platform__c,Start_Date__c  FROM CustObject WHERE Agency__c IN :agencySet AND Agency_Type__c IN :agencyTypeSet AND Advertiser__c IN :advetiserSet AND Platform__c IN :platformSet];
for (CustObject custMap : custList){
  for( CustObject oldCust : oldcustList){
    if(oldcustList.size() > 0){
       if (custMap.Start_Date__c != oldCust.Start_Date__c) {
          oldcustList.Start_Date__c = custMap.Start_Date__c;
oldList.add(oldCust);
}
}
}
update oldList;
}
}