+ Start a Discussion
Arnold Joseph TodasArnold Joseph Todas 

Duplication on Account Names

I'm creating an duplication validation on account Names. why am i getting an error of 'caused by: System.ListException: Row with null Id at index: 0 Class.AccountDuplicate.checkDuplicateName: line 7, column 1 here is my code:
public static void checkDuplicateName(List<Account> newRecords) {
    Set<String> articles = new Set<String>{'the', 'an', 'a'};
    Set<String> newNames = new Set<String>();
    Map<String, Id> newNameToAccount = new Map<String, Id>();
    Map<Id, Account> accountMap = new Map<Id, Account>(newRecords);

    for (Account account: newRecords) {
        if (account.Name == null) {

        List<String> nameParts = account.Name.split(' ');
        if (nameParts.isEmpty()) {

        for (String part: nameParts) {
            part = part.toLowerCase();
        if (articles.contains(nameParts.get(0))) {

        String newName = String.join(nameparts,' ');

        newNameToAccount.put(newName, account.Id);

    if (!newNameToAccount.isEmpty()) {
        List<Account> matchingAccounts = [
            select Name
            from Account
            where Name = :newNameToAccount.keySet()

        if (!matchingAccounts.isEmpty()) {
            for (Account account: matchingAccounts) {
                accountMap.get(newNameToAccount.get(account.Name.toLowerCase())).addError('You cannot create a duplicate name');
Thanks For Help!
Vishnu VaishnavVishnu Vaishnav
Hi Arnold ,

My understanding is that u r call this function before insert, in this case u have no ids for any record and u r using 
Map<Id, Account> accountMap = new Map<Id, Account>(newRecords);

i think u got it now...
If i m wrong then put the code that how r u calling method ?
Qusetion Solved ? then mark as best answer to make helpful to others .....