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
WikWik 

Prevent Duplicate Contact on an Account

Hi,

Need to write a trigger such that if a Contact already exists ( based on email, phone or name) on the Parent Account or any of the Parents' Child accounts, then if a user tries to Create a Contact, an error should be thrown.

This trigger should be Account based and not Org. 


Lets say a Contact is created on Account 'B'. Account 'A' is the parent for account B. and if i try to create same contact on Account 'C' ( another Child of Account 'A'), error should be thrown.

or also if the Contact exists on Parent and if we try to create  a duplicate on any of its Child, even then an error should be thrown.

I had written a trigger but that worked only on a single account.

Thank You.
Team WorksTeam Works
You will need to loop thru the account and its parent(by chewcking if it has got one parent) and collect their contacts in a map/list and then see if the contact being added is in the map/list.if yes, use add error to thorw it to user.

I hope this helps
WikWik
i had written thi:
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,Phone,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.Phone == con.Phone) && (c.id!= con.id ) ){
                       // c.Email.addError('Contact with this email address already exists.Please create a Contact Role. <a href=https://cs18.salesforce.com/02Z/e?parentId='+c.accountid+'\'>Create a Contact Role</a>',false);
                       String baseUrl = URL.getSalesforceBaseUrl().toExternalForm()+'/02Z/e?parentId=';
string errorMsg = '<a style=\'color:1B2BE8\'href="'+baseUrl+ c.accountid +'"> Please Create a Contact Role  </a>';

c.addError('This Contact already exists.'+ errorMsg,false);
                    }
                }
            }
        }
    }
}

what modifications can i bring intp it