+ Start a Discussion
SFAdmin5SFAdmin5 

bulkify trigger

i was bulk testing this trigger and while it works in the ui i get this error:

 

"setParentFieldsFromChildTriggeronProgram: execution of BeforeInsert

caused by: System.ListException: Duplicate id in list: 006G000000JvcxjIAB

Trigger.setParentFieldsFromChildTriggeronProgram: line 27, column 1"

 

Here's the trigger.  

trigger setParentFieldsFromChildTriggeronProgram on Program__c (before insert, before update) 
{              
     List<Opportunity> oppList = new List<Opportunity>();
     Set<id> Ids = new Set<id>();
     for (Program__c prgm : Trigger.new) {
         Ids.add(prgm.Opportunity__c);
        }
     
     Map<id,Opportunity> oppMap = new Map<id,Opportunity>([Select Id,Product_Group__c,Product_Area__c,Product_Family__c,Product_Family_Child__c from Opportunity Where Id in :Ids]);  
     
     for (Program__c prgm : Trigger.new) 
     {
                 Opportunity o = oppMap.get(prgm.Opportunity__c);
                 o.Product_Group__c = prgm.Product_Group__c;
                 o.Product_Area__c = prgm.Product_Area__c;
                 o.Product_Family__c = prgm.Product_Family__c;
                 o.Product_Family_Child__c = prgm.Product_Family_Child__c;
                 oppList.add(o);
     }
                 update oppList;
     
}

 

Best Answer chosen by Admin (Salesforce Developers) 
Vasu@blrVasu@blr

Instead of list take map and  update oppList, list allowes duplicates, map does not allow duplicates

 

trigger setParentFieldsFromChildTriggeronProgram on Program__c (before insert, before update) 
{              
     Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();
     Set<id> Ids = new Set<id>();
     for (Program__c prgm : Trigger.new) {
         Ids.add(prgm.Opportunity__c);
        }
     
     Map<id,Opportunity> oppMap = new Map<id,Opportunity>([Select Id,Product_Group__c,Product_Area__c,Product_Family__c,Product_Family_Child__c from Opportunity Where Id in :Ids]);  
     
     for (Program__c prgm : Trigger.new) 
     {
                 Opportunity o = oppMap.get(prgm.Opportunity__c);
                 o.Product_Group__c = prgm.Product_Group__c;
                 o.Product_Area__c = prgm.Product_Area__c;
                 o.Product_Family__c = prgm.Product_Family__c;
                 o.Product_Family_Child__c = prgm.Product_Family_Child__c;
                 oppMap.put(o.id,o);
     }
                 update oppMap.values();
     
}