i need apex trigger code to capture four field values from four parent opportunity records and need to insert those field values into four different fields into single Service(custom) object record
//Best practice is to create a class for the operations for the trigger
trigger updateService on Service__c(after insert, after update){
//Create a set of opportunityIds
Set<id> oppIdSet = new Set<id>();
//Fetch all the records associated to the given Service
for(Service__c serv : Trigger.new){
oppIdSet.add(serv .LookUpName__c);
}
//Fetch all opportunities whose belongs to given Service
List<Opportunity> oppList = [Select name,Id from Opportunity where id IN : oppIdSet];
//Then you can update the Service with the desired fields
//for loop to do your update here
for(Opportunity oppRec : oppList){
for(Service serRec : Trigger.New){
//update the service records based on your logic here
}
}
}
Please mark this as solution if this solves your problem, So that if anyone has this issue this can help.
Thanks Mudasir for your response here Service object records are not inserted manually they are created(auto populated) after opportunity records are inserted,there is one common field for those four opportunities is service type
The above code should work for you just you need to make a static variable which will stop it from recursion. Use the below code
//Best practice is to create a class for the operations for the trigger
trigger updateService on Service__c(after insert, after update){
//stop recursion
public static Boolean stopRecursion = true;
//Create a set of opportunityIds
Set<id> oppIdSet = new Set<id>();
//Fetch all the records associated to the given Service
for(Service__c serv : Trigger.new){
oppIdSet.add(serv .LookUpName__c);
}
//Fetch all opportunities whose belongs to given Service
List<Opportunity> oppList = [Select name,Id from Opportunity where id IN : oppIdSet];
//Then you can update the Service with the desired fields
//for loop to do your update here
List<Service__c> servList = new List<Service__c>();
for(Opportunity oppRec : oppList){
for(Service serRec : Trigger.New){
//update the service records based on your logic here
//servList .add(serRec );
}
}
if(stopRecursion && stopRecursion.size() > 0){
pdate servList;
stopRecursion = false;
}
}
Please mark this as solution if this solves your problem, So that if anyone has this issue this can help.
You need to have a trigger on Service.
Please mark this as solution if this solves your problem, So that if anyone has this issue this can help.
Use the below code
Please mark this as solution if this solves your problem, So that if anyone has this issue this can help.