I'm creating a trigger to update the total number of opportunity-line-items in Account record, but my code isn't working as i have 1 Account record with multiple Opportunity records, for each opportunity record we have multiple opportunity line item records.
Need the count of all the opportunityLineItems that are associated with all the opportunities for an account.
...
trigger countOfOli on OpportunityLineItem (after insert) {
Set<Id> accountIds = new Set<Id>();
Set<Id> oppIds= new Set<Id>();
for(OpportunityLineItem ol: trigger.new){
oppIds.add(ol.OpportunityId);
}
Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([select AccountId, (select Id from OpportunityLineItems) from Opportunity where id in:oppIds]);
system.debug('Opp Map'+ oppMap.values());
set<Id> accIds = new Set<Id>();
for(Opportunity opp: oppMap.values()){
accIds.add(opp.AccountId);
}
Map<Id, Account> accMap = new Map<Id, Account>([select Id, Number_of_Contacts__c from Account where Id in:accIds]);
for(OpportunityLineItem opli: trigger.new){
if(oppMap.containsKey(opli.OpportunityId) && accMap.containsKey(oppMap.get(opli.OpportunityId).AccountId)){
accMap.get(oppMap.get(opli.OpportunityId).AccountId).Number_of_Contacts__c = oppMap.get(opli.OpportunityId).OpportunityLineItems.size();
}
}
update accMap.values();
}
...