Hello Everyone, In this tutorial, We will talk about " System.ListException: Duplicate id in list" exception in Salesforce. I will let you know why this error has occurred and what step you have to take to solve this problem.
After completing this tutorial, you'll able to understand:
- Why this error happened?
- How to solve this error?
So let's begin,
In Salesforce list can hold duplicate values, but if you try to add duplicate sObject IDs in the list and then update the list you'll get the error.
For Example:
trigger AccountTrigger on Account (after insert,after update) { Id aid = '0010K00001sVwOT'; List<Account> al = new List<Account>(); for(Account a : [SELECT Id FROM Account WHERE Id ='0010K00001sVwOT']){ al.add(a); Account acc = new Account(Id = aid); al.add(acc); } update al; }
To solve this issue follow these steps:
1. Create a map of <Id,sObject>.
2. Convert the list to Map so that the duplicate IDs are removed.
3. Update the values part of the Map.
3. Update the values part of the Map.
For Example:
Id aid = '0010K00001sVwOT'; List<Account> al = new List<Account>(); for(Account a : [SELECT Id FROM Account WHERE Id ='0010K00001sVwOT']){ al.add(a); Account acc = new Account(Id = aid); al.add(acc); } MAP<Id,Account> accMap = new MAP<Id,Account>(); accMap.putall(al); if(accmap.size()>0){ update accmap.values(); }See also:
- Get IP Address in Visualforce Page
- Submit Approval Process using Apex
- Calculate Business Days in Salesforce
Conclusion:
Hope you like this tutorial, for any query or suggestions
please feel free to comment.
Thank you.
2 Comments
Thanks! it helped me.
ReplyDeleteglad to know that it helped you, keep reading.. Thanks a lot.
ReplyDeletePost a Comment