function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
$force$force 

Trigger creating duplicate records in bulk insertion.

hi guys,

 

Can u please help me in this trigger.

this trigger is inserting duplicate records in updation call and insertion is failed.

please help me in changing code.

i feel map is the gud choice in this trigger

 

trigger doc on federal__c(after insert)

 

Set<Id> sobjectSetOfIds = new Set<Id>();
List<federal__c> flist = new List<federal__c>();
 for(federal__c fs:trigger.new) {
    if(fs.Opportunity__c!=null)
     sobjectSetOfIds.add(fs.Opportunity__c);    
       flist.add(fs);
 }
 list<Conditions__c> comlist = [select id,opportunity__c,Contact__c,Federal__c from Conditions__c where opportunity__c =:sobjectSetOfIds];
 list<Conditions__c> updatedcomlist = new list<Conditions__c>();
 for(Federal__c fss :flist) {
    for(Conditions__c cm: comlist) {     
            cm.federal__c=fss.id;         
            updatedcomlist.add(cm);
        }
    }
    upsert updatedcomlist;
}

 

Thanks

$f

 

Dirk GronertDirk Gronert

What about changing

 

 list<Conditions__c> comlist = [select id,opportunity__c,Contact__c,Federal__c from Conditions__c where opportunity__c =:sobjectSetOfIds];

 

To

 

 list<Conditions__c> comlist = [select id,opportunity__c,Contact__c,Federal__c from Conditions__c where opportunity__c in :sobjectSetOfIds];

 

And: your trigger is only executed "after insert" and not for any update operations!!

 

trigger doc on federal__c(after insert) ...

 

Furthermore: do not use dml operations in a for-loop - there are gov-limits!!

 

 list<Conditions__c> updatedcomlist = new list<Conditions__c>();
 for(Federal__c fss :flist) {
    for(Conditions__c cm: comlist) {     
            cm.federal__c=fss.id;         
            updatedcomlist.add(cm);
        }
    }
    upsert updatedcomlist; >>>>>>> remove this one
}

upsert updateedcomlist; >>>>>>>> and paste it after the outer bracket!

 

If you are still facing problems pls post the exception/message you are getting!

 

--dirk