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
MRDJMRDJ 

Trigger to prevent duplicate and delete old records when new record is inserted

I need help on the below requirement.
Project_Creation__c is custom object,
Identifier_pcm__c is the external id field on that object.

In this object, records are created from online and Mobile.
If the record is created from online and the same record already exists based on external id field (Identifier_pcm__c) match, then should throw error message in online
If the record is created from Mobile and the same record already exists based on external id field (Identifier_pcm__c) match, then delete the existing (old) record and replace with new record.

Here is the code I have written but not working. Can someone help me.
trigger Project_Creation_Duplicate_Check on Project_Creation__c (before insert) 
{
    //Map to store the id and Identifier (field) of each Project Creation record that comes into the trigger so we can use that to do a SOQL query later when its time to see if it already exists.  add the 'trigger.isBefore' even though we know this will only occur before, so that this can be easily extended in the future and we wont have to go back and change code.
    //Map<String, Project_Creation__c> mappcm = new Map<String, Project_Creation__c>();
    
    //create a list of all related accounts
    //List<id> relatedAccounts = new List<id>();
    //for(Project_Creation__c pcm : Trigger.new)
    //{
        //relatedAccounts.add(pcm.Identifier_pcm__c);
    //}
    //create a map of Account with Project Creation data
    Map<id, List<Project_Creation__c>> mapAccounttopcms = new Map<id, List<Project_Creation__c>>();
    for(Project_Creation__c pcmRecords : Trigger.new)
    {
        if((pcmRecords.Identifier_pcm__c != null) && (Trigger.isInsert || (pcmRecords.Identifier_pcm__c != Trigger.oldMap.get(pcmRecords.Id).Identifier_pcm__c)))
        {
            if(mapAccounttopcms.containsKey(pcmRecords.Identifier_pcm__c) && pcmRecords.Mobile_ID__c == null)
            {
                pcmRecords.Identifier_pcm__c.addError('You are creating a duplicate record. ' + 'We recommend you use an existing record instead.');
            }
            if(mapAccounttopcms.containsKey(pcmRecords.Identifier_pcm__c) && pcmRecords.Mobile_ID__c != null)
            {
                mapAccounttopcms.get(pcmRecords.Identifier_pcm__c).add(pcmRecords);
            }
            else
            {
                mapAccounttopcms.put(pcmRecords.Identifier_pcm__c, new List<Project_Creation__c>{pcmRecords});
            }
        }
    }
    
    // Using a single database query, find all the project creations in  
    // the database that have the same Identifier as any  
    // of the project creations being inserted or updated.  
    
        for(Project_Creation__c pcm : [Select Identifier_pcm__c FROM Project_Creation__c WHERE Identifier_pcm__c IN :mappcm.keySet()])
        {
            Project_Creation__c newpcm = mapAccounttopcms.get(pcm.Identifier_pcm__c);
            newpcm.Identifier_pcm__c.addError('You are creating a duplicate record. ' + 'We recommend you use an existing record instead.');
        }
        
    //iterate over the map mapAccounttopcms and add any duplicate values to a list
    List<Project_Creation__c> toDelete = new List<Project_Creation__c>();
    for(Project_Creation__c pcm : trigger.new)
    {
        List<Project_Creation__c> pcmRecordList = new List<Project_Creation__c>();
        pcmRecordList = mapAccounttopcms.get(pcm.Identifier_pcm__c);
        
        if(pcmRecordList!=null && pcmRecordList.size()>0)
        {
            for(Project_Creation__c am : pcmRecordList)
            {
                if(pcm.Identifier_pcm__c == am.Identifier_pcm__c)
                {
                    toDelete.add(am);
                }
            }
        }
    }
    if(!toDelete.isEmpty())
    {
        try
        {
            Database.delete(toDelete);
        }
        catch(DMLException e)
        {
            String logMsg = '';
            for (Integer i=0; i<e.getNumDml(); i++) 
            {
                logMsg = e.getDmlType(i) + ': ' + e.getDmlMessage(i);
                String[] errFlds = e.getDmlFieldNames(i);
                if (errFlds != null) 
                {
                    logMsg += '(';
                    for (Integer j=0; j<errFlds.size(); j++) 
                    {
                        if (j>0)logMsg += ', ';
                        logMsg += errFlds[j];
                    }
                }
            }
            // Error found, keep user on same page to display messages
            System.debug('SFDC Project Creation Record deletion Trigger threw the following exception: ' + e.getMessage() + logMsg);
        }
    }
}

 
Alain CabonAlain Cabon
Hello,

 (before insert) only.

The problem is here: if((pcmRecords.Identifier_pcm__c != null) && (Trigger.isInsert || 
    (pcmRecords.Identifier_pcm__c != Trigger.oldMap.get(pcmRecords.Id).Identifier_pcm__c)))


Alain
MRDJMRDJ
Hi Alain,

Thanks for your reply. I have made the changes as per your suggestion but it didn't work.