• Shubham Gupta 298
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi ,

I have written a piece of trigger , trying to prevent duplicate contacts on an Account:

trigger PreventDuplicateContact on Contact (before insert, before update){

Set<id> accid = new Set<id>();
for (Contact c : Trigger.new)
accid.add(c.Accountid);

Map<Id,list<contact>> AccEmails = new Map<Id,list<contact>>();
Map<Id, Contact> cont = new Map<Id, Contact> ([Select Email from Contact where Id in:accid]);

for (Contact c : Trigger.new){
if ((contact.Email !=null) && (System.Trigger.isInsert ||(contact.Email != System.Trigger.oldMap.get(contact.Id).Email))){
if ( cont.containsKey(contact.Email)){
Contact co = cont.get(contact.Email);
if(co.accountid==contact.accountid){
contact.Email.addError('Another new contact has the '+'same email address.');
            }else{
                cont.put(contact.Email,c);
     }}
       }
    }
    for (Contact c : [SELECT Email FROM Contact WHERE Email IN :cont.KeySet()]){
        Contact newContact = cont.get(c.Email);
        newContact.Email.addError('A Contact with this email '+'address already exists.');
   }
}

But this is not working as expected. Please help me get it modified
  • September 01, 2014
  • Like
  • 0