I need help in following code-
I have Custom field on Account as Custom_Id__c(Text 255). Scenario is you can create only 2 accounts with same value in Custom_Id__c field.
example - Account 1 - custom_Id__c= 'abcd' Account 2 - custom_Id__c= 'abcd' Account 3 - custom_Id__c= 'abcd' - Must show error'
below code works fine for single record but not for mulitple.
public with sharing class AccountTriggerAction {
/*
Method Name - validateAccount
Description - This method validates if there are Two Accounts are present with Same Custom Id. If yes
then this will throw an Error and will not allow User to Add Third Account with Same Custom Id
Param - List<Account> - List of New Accounts
*/
public static void validateAccount(List<Account> newAccounts){
//Map of Custom Id to its Related Account List
Map<String, List<Account>> mapOfCustIdToListOfAccount = new Map<String, List<Account>>();
List<Account> lstAccount = new List<Account>();
for(Account account:newAccounts){
mapOfCustIdToListOfAccount.put(account.Custom_Id__c, Null);
}
//Fetching Old Accounts which are present in database with Same Custom Id which we are inserting
List<Account> oldAccounts = [SELECT Id, Custom_Id__c FROM Account
WHERE Custom_Id__c =: mapOfCustIdToListOfAccount.Keyset() LIMIT 50000];
if(oldAccounts.size()>0){
for(Account objAccount: oldAccounts){
if(mapOfCustIdToListOfAccount.containsKey(objAccount.Custom_Id__c)){
lstAccount.add(objAccount);
}
}
}
for(Account newAcc : newAccounts){
if(lstAccount.size() == 2){
newAcc.Custom_Id__c.addError('Only Two Accounts are allowed with Same Custom Id -- '+ newAcc.Custom_Id__c);
}
}
}
}