About this question
I need to check if a record which is getting inserted has a duplicate. If there is one, then change a boolean field (Is_latest__c) to true in the inserted record and update the duplicate's field to false. I have created a before insert trigger, and in this trigger I check if a duplicate exists and change the Is_latest__c field of the inserted record to true. But when I try to update the old duplicate value in the trigger I am getting error that
System.DmlException: Update failed. First exception on row 0 with id afdfd9000000hxuSAEAY; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, lastupdate: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id arfg45000000hxuSAEAY; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = artr9000000hxuSA) is currently in trigger lastupdate, therefore it cannot recursively update itself
Is there any solution for this issue?
My code:
trigger lastupdate on Visit__c(before insert, before update) {
if(Trigger.isBefore) {
visitTriggerHandler vTH = new visitTriggerHandler();
vTH.beforeInsertTrigger(Trigger.new);
}
}
public class visitTriggerHandler {
public SetcontactFieldSet = new Set public Set(); projectFieldSet = new Set public Set(); surveyFieldSet = new Set public List(); visitList = new List Map(); visitBeforeInsertMap = new Map ();
public void beforeInsertTrigger(MapvisitBeforeInsertMaps, List for(Visit__c visitToMap : visitBeforeInsertList) {visitBeforeInsertList) {
visitBeforeInsertMap.put(visitToMap.Id, visitToMap);
}
for(Visit__c visit : visitBeforeInsertList) {
contactFieldSet.add(visit.Contact__c);
projectFieldSet.add(visit.Project_Group__c);
surveyFieldSet.add(visit.Survey__c);
}
visitList = [SELECT Id FROM Visit__c
WHERE Survey__c IN :surveyFieldSet
AND Contact__r.Id IN :contactFieldSet
AND Project_Group__c IN :projectFieldSet
AND Is_latest__c = true];
if(visitList.size() > 0) {
for(Visit__c islastUpdate : visitBeforeInsertList) {
islastUpdate.Is_latest__c = true;
}
}
//visitList.add(islastUpdate);
visitBeforeInsertList = visitBeforeInsertMap.values();
//update visitList;
}
}