+ Start a Discussion
bohemianguy100bohemianguy100 

preventing duplicate records from getting inserted

I have the following method that takes as an argument a list of fulfillments:

 

public static void processRelatedAccounts(List<Fulfillment__c> fulfillments) { Set<String> TopLevelAccountIds = new Set<String>(); Set<Id> originalAccountIds = new Set<Id>(); for (Fulfillment__c f : fulfillments) { TopLevelAccountIds.add(f.Parent_Account_Id_Top_Level__c); } for (Fulfillment__c f : fulfillments) { originalAccountIds.add(f.account__c); } Map<String, List<Account>> mapRelatedAccounts = new Map<String, List<Account>>(); List<Account> relatedAccounts = [Select Id From Account Where Parent_Account_Id_Top_Level__c in: TopLevelAccountIds AND Id not in: originalAccountIds]; List<Fulfillment__c> fuls = new List<Fulfillment__c>(); for (Fulfillment__c f: fulfillments) { mapRelatedAccounts.put(f.Parent_Account_Id_Top_Level__c, relatedAccounts); } for (Fulfillment__c f : fulfillments) { if (mapRelatedAccounts.containsKey(f.Parent_Account_Id_Top_Level__c)) { List<Account> accountsFromMap = mapRelatedAccounts.get(f.Parent_Account_Id_Top_Level__c); for (Account a : accountsFromMap) { Fulfillment__c ful = new Fulfillment__c(); ful.Contact__c = f.Contact__c; ful.Account__c = a.Id; ful.Fulfillment_Request__c = f.Fulfillment_Request__c; fuls.add(ful); } } } insert fuls; }

 

 

Each fulfillment has an (Account)Lookup field named Account__c.  In the last section of code where I have the nested loop and am looping thru each fulfillment, how can I check if the next iteration of the outer loop (fulfillment__c) has the same account id?

 

I don't want to process the inner loop that creates new fulfillments for the same account id.

 

For example, if I pass in 4 fulfillments and the first two fulfillments have Test Account 1 and the next 2 fulfillments have Test Account 2.  I only want to process the fulfillments for Test Account 1 and Test Account 2 only once.  Not twice.

 

How can I check if the accountId has already been processed?

 

Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
waylonatcimwaylonatcim
What about using a collection, set for example, to store all of the fulfilments that you have processed (or the id's of the fulfillments).  Then, before processing a new fulfillment just check the set to see if you have already processed that partuclar one.