0

My requirement is to perform the bulk insert(50 or 60 records), and restrict duplicate contacts. My trigger is working for 1 record, but not for many at the same time.

Here is my trigger:

Trigger duplicatecOn on Contact (before insert) 
{
    List<Account> accList = new List<Account>();
    Set<Id> accIdSet = new Set<Id>();
    for(contact con : trigger.new)
    {
        accIdSet.add(con.accountId);
    }

    Map<Id, Account> accountsMap = new Map<Id, Account>([Select id, name, (Select id, lastname From Contacts) From Account
                                                            Where Id IN : accIdSet]);
    for(contact con : trigger.new)
    {
        Account acc = accountsMap.get(con.accountId);
        for(Contact cont : acc.contacts)
        {
            if(con.lastname == cont.lastname)
            con.addError('Contact with same name already exists');
        }
    } 
}
2
  • 1
    Please be more specific about what you mean when you say it is not working. – Adrian Larson Sep 28 '16 at 14:36
  • 1
    To expand on Adrian's comment, we aren't mind readers. I can make a guess as to what you mean by "it isn't working", but guessing about what isn't working is nowhere near as good as knowing how it isn't working. It's much better to say thing 'x' is what I expect to happen, but a different thing, thing 'y', is happening instead. Generally speaking, the more (relevant) details that you include, the better the quality of answers that you'll receive. – Derek F Sep 28 '16 at 14:57
0

The problem here is that you are only ever checking your new records against existing records - and never updating the existing records with new records. So if you have an Account with 1 contact (Smith) and you are loading in 3 Contacts (Smith, White, White) - given this code Smith would fail but both Whites would be inserted, that is because once you process the first White you need to add it to the accountsMap so the second White will detect it.

for(contact con : trigger.new)
{
    boolean errored = false;
    Account acc = accountsMap.get(con.accountId);
    for(Contact cont : acc.contacts)
    {
        if(con.lastname == cont.lastname){
        con.addError('Contact with same name already exists');
        errored = true;
        } 
    }
    if(!errored){
        //Add con to accountMap
    }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.