+ Start a Discussion
Shyamala VaradharajanShyamala Varadharajan 

Update Existing Record before Inserting new record to avoid duplication

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 . 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.I have written this in before Insert. please help.
 
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;
}
}
MagulanDuraipandianMagulanDuraipandian
Shyamala,
This is expected behaviour. If you use addError to throw an error to preven creation of record the update will also fail.

Option1:
Use Queueable interface to update the old record.
Use addError and throw an error to avoid inserting the new record.

Option 2(Recommended):
Use Duplicate rule and show it on the screen.
https://www.infallibletechie.com/2016/05/how-to-avoid-duplicate-in-custom-object.html
PriyaPriya (Salesforce Developers) 
Hey Shyamla,

Kindly implement the duplicate rule in your org for that object

Thanks
Shyamala VaradharajanShyamala Varadharajan
Hi,

I want to know how to update old record with the new value while inserting.

Thanks
Wish 25Wish 25
Hi, 

There is a findDuplicate Class in Apex. You can use that to find if there is a record exist with the same values. If it does, fetch that record using SOQL and update the record. Check below link:

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Datacloud_FindDuplicates.htm