0

What I would like to achieve via automation is to record the created date of the latest record on the retained record after merging.

Example: A new lead comes in on 01/01/22 and a duplicate lead is found dating back to 15/06/2019. A user merges the two together and the create date remains as 15/06/2019 regardless which you choose as master. I have a custom field called 'Latest enquiry date' that I would like to update with 01/01/22.

I realise this can be done manually during the merge process but I'd prefer an automated solution to ensure this is done every time. When leads are merged in Salesforce, I don't believe there is a merge or create trigger fired, just update and delete triggers so I'm struggling to find when to fire a field update.

Any suggestions welcome.

1 Answer 1

1

In the after-delete trigger on Leads, you'll have a populated value in the MasterRecordId field, which you can use to determine how you'd like to update your custom field.

trigger ManageLatestEnquiryDate on Lead (after delete) {
  Map<Id, Lead> masterLeadRecords = new Map<Id, Lead>();
  for(Lead record: Trigger.old) {
    masterLeadRecords.put(record.MasterRecordId, null);
  }
  masterLeadRecords.putAll([SELECT CreatedDate, Latest_Enquiry_Date__c FROM Lead WHERE Id = :masterLeadRecords.keySet()]);
  masterLeadRecords.remove(null);
  for(Lead record: Trigger.old) {
    Lead masterLeadRecord = masterLeadRecords.get(record.MasterRecordId);
    if(masterLeadRecord != null) {
      Date tempDate; 
      if(masterLeadRecord.CreatedDate > record.CreatedDate) {
        tempDate = masterLeadRecord.CreatedDate;
      } else {
        tempDate = record.CreatedDate;
      }
    }
    if(masterLeadRecord.Latest_Enquiry_Date__c == null || masterLeadRecord.Latest_Enquiry_Date__c < tempDate) {
      masterLeadRecord.Latest_Enquiry_Date__c = tempDate;
    }
  }
  update masterLeadRecords.values();
}

Ideally, you should use a trigger handler framework, but this basic version should suffice if you just need to get a solution started.

2
  • Thanks for this, very helpful. Unless you or anyone else can offer a solution using Flows, I'll mark this as best answer. Is there an 'after delete' option in Flows yet? May 10, 2022 at 10:12
  • @AndrewJones Apex is the only thing that can directly respond to a delete event, but if you really wanted to, you could create an autolaunched flow and call that from Apex. Not sure if that's worth the effort, since the code is already small enough as is.
    – sfdcfox
    May 10, 2022 at 10:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .