I updated my question as my trigger is failing because of some other trigger.
I created a trigger on Opportunity object, So i am trying to insert object1 and object2 records based on some condition. I am using object1 id in object2. In my code i used DML operation inside for loop can anyone help me how to avoid it.
public class TriggerHandlerClass {
public static void updateValues(List<Opportunity> oppLst){
List<Custom_Object_1 > object1 = new List<Custom_Object_1 >();
List<Custom_Object_2> object2List = new List<Custom_Object_2>();
List<Custom_Object_3> Object3Entry = [select Id, Label__c,Type__c, product__r.Name, product__r.Family, product__r.Description from Custom_Object_3 Where Label__c = 'Technology' ];
map<Id, Custom_Object_1 > mapOpportunityIdToMR = new map<Id, Custom_Object_1 >();
for (Opportunity objOpportunity : oppLst) {
if ((objOpportunity.field__C == 'SOmething') )
Custom_Object_1 Ob1Reg = new Custom_Object_1 ();
Ob1Reg.Name = objOpportunity.FirstName +' '+ objOpportunity.LastName;
Ob1Reg.closeDate__C =System.today()+90;
mapOpportunityIdToMR .put(objOpportunity.Id, Ob1Reg);
insert ob1Reg;
Custom_Object_2 dealProd = new Custom_Object_2();
dealProd.Amount__c = 450;
dealProd.Line_Description__c = 'text';
dealProd.lookupField_CustomObject_3__C = Object3Entry[0].ID;
dealProd.lookupField_CustomObject_2__C = Ob1Reg.ID;
object2List.add(dealProd);
}
}
insert object2List;
// insert mapOpportunityIdToMR .Values();
List<Opportunity> oppLstToUpdate = new List<Opportunity>();
for(Id opportunityId: mapOpportunityIdToMR.keyset())
{
oppLstToUpdate.add(new Opportunity(Id = OpportunityId, Custom_Object_1_lookup = mapOpportunityIdToMR .get(OpportunityId).Id));
}
// update Opportunity
update oppLstToUpdate;
}
}
Trigger :
TriggerHandlerClass.updateValues(Trigger.New);
dealProd.lookupField_CustomObject_2__C = Ob1Reg.ID;
,Ob1Reg.Id
will be null until after you insert the record.