Restricting the user to create duplicate email(Contact) for a particular account

Apex class
--------------
public class DuplicationOnContact {
    public static void doDuplicateCheck(List<Contact> conlist){
         Map<String,String> mapcon=new Map<String,String>();
        set<String> setacc=new set<String>();
        for(Contact con:conlist){
            if(con.AccountId!=null)
                setacc.add(con.AccountId);
                }
 
    for(Contact con:[select Id,Name,Email,AccountId from Contact where AccountId=:setacc]){
         mapcon.put(con.Email,con.AccountId);
    }
    for(Contact con:conlist){
        if(!mapcon.isEmpty() &&  mapcon.containskey(con.Email)){
            con.addError('Please enter unique Email');
        }
    }

    }
}

Trigger
----------
Trigger ContactTrigger on Contact(before insert,before update){
       DuplicationOnContact.doDuplicateCheck(Trigger.new);

   }

//It will be fired when the user creates a contact with email(which already present in the database) for a particular account






Comments

  1. Great work done by you .Informative and problem-solving content that users can easily digest can work really great for almost all types of blogs. When a user find something informative on a blog, he/she is more likely to come back again in future to get something valuable from your side.




    Assignment Writing Help

    ReplyDelete
  2. why trigger. we can achieve this by duplicate rules right ! just configuration.

    ReplyDelete
    Replies
    1. Hi Satish, it was requested by one of the Salesforce developers so I added in my blog.

      Delete

Post a Comment