+ Start a Discussion
Michael MMichael M 

Before insert record to find and edit matching record

We have a custom object called Discharges. Before a new Discharge is inserted, I need to check to see if that person already has a Discharge record in the database. (Right now, I am just checking by name.) If they do have an existing record, I need to:
1. Make an update on the existing record (name_external_id__c)
2. Populate several fields on the new record based on data from the existing record.   

I'm not sure if this is the best way, but so far I added a custom field called "parent discharge" which is a lookup to itself. Is that the best way? And even if it is, once it is linked, how would I update the old record and populate the new one based on the old? Here is my trigger that I've written so far, but even this does not seem to work/ it is not automatically populating the lookup field. 

trigger DischargeTrigger on Discharge__c (before insert) {
   Set<String> newNameSet   = new Set<String>();
   Map<String,Id> oldNameMap    = new Map<String,Id>();
    for (Discharge__c disch : trigger.new){
        if (disch.Name != null && disch.Other_Diagnosis_ICD_Descriptions__c !=null ){
        for (Discharge__c oldDis : [SELECT Id, name, name_external_id__c, Discharge_Recurral__c, Previous_Discharge_Instances__c FROM Discharge__c WHERE name =:newNameSet]){
                 oldNameMap.put(oldDis.name, oldDis.id);
    if(oldNameMap.size() > 0){
        for (Discharge__c dis : trigger.new){
            if (dis.name != null && oldNameMap.get(dis.name)!= null){
                dis.Parent_Discharge__c= oldNameMap.get(dis.name);

Any help is greatly appreciated.

Best Answer chosen by Michael M
Jakub Kołodziej 7Jakub Kołodziej 7
Why trigger?
Not better to create process + flow which will check for duplicates and make changes?