Trying to create a trigger to prevent creation of duplicate accounts

This is the trigger i have wrote to prevent the creation of duplicate accounts, i am getting an error message saying “Intial term of field expression must be a concrete SObject:LIST “.

Can someone help me in scrubbing this code, so that it might work.
thanks.

trigger AccountDuplicateTrigger on Account (before insert,before update) {
    for(Account a:Trigger.new)
    {
        List<Account> acc=[select ID from account where Name=:a.Name and Rating=:a.rating];
        if(acc.size()>0)
        {
            acc.name.adderror('You cannot create a dulplicate account');
        }
    }
}

Answer

@Shebin answered your specific question, but there are a few issue with your trigger, the most important being that it is not bulkified. you always want to avoid SOQL inside loops.

Something like below is a bit safer to use

trigger AccountDuplicateTrigger on Account (before insert,before update) {

     //You may need to filter this a bit more if you have a very large number of accounts    
     map<Id,Account> existingAccountMap = new  map<Id,Account>([Select Id, Name, Rating From Account Where Rating != null]); 

     for(Account a : Trigger.new){
        //Remember to use Double equal
        if(a.name == existingAccountMap.get(a.Id).Name && a.rating == existingAccountMap.get(a.Id).rating){
          a.adderror('You cannot create a dulplicate account');
        }
     }
}

Attribution
Source : Link , Question Author : Prashanth , Answer Author : Brian

Leave a Comment