You need to sign in to do that
Don't have an account?

Trigger to count Opportunities related to the Contact
Hello Developers,
I have the trigger below that counts the number of Opportunities that are assigned to the Account and displays them on the Contact redord. I need this trigger to only count the Opportunities that the Contact is assigned to via the Opportunity Contact Role and the field in the Opportunity called STS Currently Engaged is TRUE. Any assistance will be greatly appreciated!!
I have the trigger below that counts the number of Opportunities that are assigned to the Account and displays them on the Contact redord. I need this trigger to only count the Opportunities that the Contact is assigned to via the Opportunity Contact Role and the field in the Opportunity called STS Currently Engaged is TRUE. Any assistance will be greatly appreciated!!
trigger RollUpSTSOpportunity on Opportunity (after delete, after insert, after update) { set<Id> setAccountIds = new set<Id>(); map<Id, Integer> mapAccountToOpp = new map<Id, Integer>(); List<Contact> lstContactUpdate = new List<Contact>(); if(trigger.isInsert || trigger.isUpdate) { for(Opportunity o : trigger.new) { setAccountIds.add(o.AccountId); // take all the related Account Id's in a set from trigger.new in case of insert/update } } else { for(Opportunity o : trigger.old) { setAccountIds.add(o.AccountId); // take all the related Account Id's in a set from trigger.old in case of delete } } for(Account a : [Select Id, (Select Id From Opportunities) From Account Where Id In :setAccountIds]) { mapAccountToOpp.put(a.Id, a.Opportunities.size()); // add each account id with the number of opportunities related to it } for(Contact c : [Select Id, AccountId, Related_STS_Opportunities__c From Contact Where AccountId In :mapAccountToOpp.keySet()]) { c.Related_STS_Opportunities__c = mapAccountToOpp.get(c.AccountId); // from the contact, we can get the number of opp related to it's parent account lstContactUpdate.add(c); } if(lstContactUpdate.size() > 0) update lstContactUpdate; // update the contacts }
Hi Harmens,
This logic will roll up those count of opportunity who are associated with contact to Account .Below is code snippet to support your use case : -
All Answers
Just query the opps in every contact WHERE STS Currently Engaged == True. The size of that list should be the number of opps it has.
Or am I getting it wrong?
Thank you for the reply.
How do "query the opps in every contact WHERE STS Currently Engaged == True. The size of that list should be the number of opps it has."
if(contacts.size()>0){
for(contact c : contacts){
c.number_of_opportunities__c = c.opportunities.size(); //should be the name of the field you are using to count the opps.
}
}
if(contacts.size()>0){
update contacts;
}
Something like that.
Hi Harmens,
This logic will roll up those count of opportunity who are associated with contact to Account .Below is code snippet to support your use case : -