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
Antony RaphelAntony Raphel 

Duplicate record Validation for Related Contacts of an Account

Hi I have activated relate one contact to Multiple Accounts. Now I would like to add a Validation/Trigger to stop adding duplicate Contacts (lest sat Same First Name and Last name) as a Direct or Indirect contacts to that account. How can we achieve this?
SandhyaSandhya (Salesforce Developers) 
Hi,

Below is the sample code to prevent duplicate contacts on the account and try to modify the code according to your requirement.
 
trigger PreventDuplicateContact on Contact (before insert,before update) {
    
    if(trigger.isInsert || trigger.isUpdate)
    {
        Map<Id,List<Contact>> accMap = new Map<Id,List<Contact>>();
        List<Contact> contactList;
        
        for(Contact c: [Select Id,Email,accountId from Contact]){
            if(accMap.containsKey(c.accountId)){   
                accMap.get(c.accountId).add(c);
            }
            else{
                contactList = new List<Contact>();
                contactList.add(c);
                accMap.put(c.accountId,contactList);
            }       
        }
        
        for (Contact c : Trigger.new) 
        {
            if(accMap.containsKey(c.accountId)){
                for(Contact con : accMap.get(c.accountId)){
                    if(c.Email == con.Email){
                        c.Email.addError('Contact with this email address already exists');
                    }
                }
            }
        }
    }
}

https://developer.salesforce.com/forums/?id=906F0000000Ah6YIAS

Hope this helps you!


If this helps you, please mark it as solved.

Thanks and Regards
Sandhya