+ Start a Discussion
MMA_FORCEMMA_FORCE 

System.ListException: Duplicate id in list:??? Help in Trigger Please

Hi:

   I am getting duplicate ID's in my trigger when really there are no dups in my list???

Where am I going wrong:

 

trigger updateSubjectArea on Subject_Area_RQ__c (after insert,after update) {
 List<Subject_Area__c> htoUpdte = new List<Subject_Area__c>();
Subject_Area__c sa;
Set <ID> setOrderId = new set<ID>();
for (Subject_Area_RQ__c orderDetail :trigger.new) 
    {
    setOrderId.add(orderDetail.Subject_Area__c);
    }
 
List<Subject_Area__c> accounts = [SELECT Id FROM Subject_Area__c where Id IN :setOrderId];

for(Subject_Area_RQ__c sar : trigger.new){ 
for(Subject_Area__c a: accounts){
         a.SARQ__c = sar.On_Track_Subject_Area__c;
System.Debug('a.SARQ__c - ' +sar.On_Track_Subject_Area__c);
htoUpdte.add(a);
}
update htoUpdte; 
}
}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
ahab1372ahab1372

you don't have have to add the accounts to yet another list. Delete the htoUpdate.add(a) and update your list "accounts" instead.

All Answers

SuperfellSuperfell

You add all of the records from the accounts list to htoUpdate for every record in the trigger, so if the trigger is for more than one record, then you'll have duplicates in the htpUpdate list.

ahab1372ahab1372

you don't have have to add the accounts to yet another list. Delete the htoUpdate.add(a) and update your list "accounts" instead.

This was selected as the best answer
MMA_FORCEMMA_FORCE

Thank you Both I decided to do the trigger this way: hmm Do you see any issues with this code?

 

trigger updateSubjectArea on Subject_Area_RQ__c (before insert,before update) { 
Map<Id, Subject_Area_RQ__c> SARQ = new Map<Id, Subject_Area_RQ__c>();
for (Integer i = 0; i < Trigger.new.size(); i++) {
        SARQ.put(Trigger.old[i].Subject_Area__c,Trigger.new[i]);
    }
List<Subject_Area__c> updatedSARQField = new List<Subject_Area__c>();

for (Subject_Area__c sa : [SELECT id, SARQ__c
                      FROM Subject_Area__c
                      WHERE Id 
                            in :SARQ.keySet()]) {
        Subject_Area_RQ__c parentAccount = SARQ.get(sa.id);
        sa.SARQ__c = parentAccount.On_Track_Subject_Area__c;
        System.Debug('parentAccount ' + parentAccount.On_Track_Subject_Area__c + ' parentAccountAll - ' + parentAccount);
        
        updatedSARQField.add(sa);
    }
    update updatedSARQField;
}