You need to sign in to do that
Don't have an account?
How to take Query out of Loop - particular instance
Hi all-
Beginning developer that has been running my head into the wall with this trigger for a while now. I feel like I am missing something obvious but I don't know where it is.
I have reciently implemented Campaign Influence for my organization. (for those of you who have not used Campaign Influence - it is related to the Opportunity and Contact Roles. When a contact role is related to an opportunity, the Campaign influence will pull in the Campaigns related to the contact so they are automatically associated to the campaign.)
I have a requirement that all Campaigns related to a contact must be split equally. I've tried various ways to pull the Query of related campaign influences, but have found that when I attempt to do a bulk upload, the trigger will combine campaigns two different opps, then divide by the total.
(ie. Opp 1 has 3 related campaign influence and opp 2 has 3 related campaign influence. Instead of attributing 33% influence to each, I end up with 17%).
The below trigger works, but I understand that the trigger should not be in the loop and I would like to improve it.
Thank you!
trigger UpdateOppPrimaryCampaign on Opportunity (after update) { for(Opportunity o : trigger.new) { List<String> oppListId = new List<String>(); system.debug('First for loop runs'); oppListId.add(o.Id); system.debug('oppListId = '+oppListId); List<CampaignInfluence> relatedCampaignInfuence = [SELECT Id, CampaignId, Influence, OpportunityId FROM CampaignInfluence WHERE OpportunityId IN :oppListId]; List<CampaignInfluence> campaignInfluenceListUpdate = new List<CampaignInfluence>(); system.debug('relatedCampaignInfuence = '+relatedCampaignInfuence); for(campaignInfluence c : relatedCampaignInfuence){ Decimal numCampaign = relatedCampaignInfuence.size(); system.debug ('numCampaign = ' + numCampaign); Decimal percentCampaign = 100 / numCampaign; system.debug ('percentCampaign = '+ percentCampaign); c.Influence = percentCampaign; system.debug('c.Influence = '+ c.Influence); c.Influenced__c = percentCampaign; campaignInfluenceListUpdate.add(c); system.debug('campaignInfluenceListUpdate = ' + campaignInfluenceListUpdate); } system.debug('update campaignInfluenceListUpdate EXECUTES'); Database.SaveResult[] results = Database.update(campaignInfluenceListUpdate, false); } }
based on which field you update what field on what object. then i will give you the exact solution.
Can you try below code
for(campaignInfluence c : relatedCampaignInfuence){
Integer numCampaign = c.size();
system.debug ('numCampaign = ' + numCampaign);
Decimal percentCampaign = 100 / numCampaign;
system.debug ('percentCampaign = '+ percentCampaign);
c.Influence = percentCampaign;
system.debug('c.Influence = '+ c.Influence);
c.Influenced__c = percentCampaign;
campaignInfluenceListUpdate.add(c);
system.debug('campaignInfluenceListUpdate = ' + campaignInfluenceListUpdate);
}