function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Arnold Joseph TodasArnold Joseph Todas 

Duplication of Name in Account

How can i ignore the word of The, An, A in when i create an account Name for example The Company = Company; An Company = Company; it should show an error and it will not added to the list. And how can i put the SELECT query outside the loop here is my code : 
public static void checkDuplicateName(List<Account> newRecord){         
        Set<String> str = new Set<String>{'The','An','A'};
        for(Account account: newRecord){              
            List<Account> existingName = [SELECT Id, Name FROM Account WHERE Name =: account.Name];
            if(existingName.size()>0){
                account.adderror('You cannot create a duplicate Name');
            }
        }
    }

Thanks For Help!
AJ
pconpcon
You can do something like this.  It avoids having SOQL inside your loop.
 
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) {
            continue;
        }

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

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

        String newName = nameParts.join(' ');

        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');
            }
        }
    }
}

NOTE: This code has not been tested and may contain typographical or logical errors.
Arnold Joseph TodasArnold Joseph Todas
sir pcon,

 unexpected token: '{' at line 23 column 48, i'm newbie here.

Thank you !
AJ
Arnold Joseph TodasArnold Joseph Todas
Sir pcon,


error in String newName = nameParts.join(' ');
Method does not exist in String.

Thanks!
AJ