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){
   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()){
    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();   

1 Answer 1


Your trigger is overly complicated. All you need is:

Map<Id, Account> accounts = new Map<Id, Account>();
for(Opportunity record: Trigger.new) {
  accounts.put(record.AccountId, new Account(Id=record.AccountId, Total_Line_Items__c=0));
for(AggregateResult result:[SELECT COUNT(Id) sum, Opportunity.AccountId accountId FROM OpportunityLineItem WHERE Opportunity.AccountId = :accounts.keySet() GROUP BY Opportunity.AccountId]) {
  Id accountId = (Id)result.get('accountId');
  Integer sumCount = (Integer)result.get('sum');
  accounts.get(accountId).Total_Line_Items__c = sumCount;
update accounts.values();
  • the above solution looks like the count of childs updating in parent. But what i'm looking is updating grand-child's count into Parent record. My requirement is Parent ---> Child1,Child2,and so on ---> grandChild11,grandChild12, grandchild21, grandchild22 and so on, from this requirement i need the total grand child records count to be populated in Parent record.
    – Sindhu V
    Aug 22, 2020 at 20:21
  • @SindhuV I'm updating the Account with the Account's Opportunities' Line Items. Isn't that what you asked for?
    – sfdcfox
    Aug 22, 2020 at 21:03
  • yes but actually when I try to insert multiple line items associated to different opportunities under different accounts in developer console, the count is not updating as expected. Is there any alternate approach to aggregate results.
    – Sindhu V
    Aug 23, 2020 at 6:58
  • @SindhuV You'd want to write a unit test to try and isolate the problem. It should work.
    – sfdcfox
    Aug 23, 2020 at 9:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .