function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kashyap JoshiKashyap Joshi 

Trigger to count Total no of Orders of Particular Customer and update On Account and Case custom field

PriyaPriya (Salesforce Developers) 

Hi Kashyap,

Can you please elaborate your requirment ?

Regards,

Priya Ranjan

Kashyap JoshiKashyap Joshi

Hi Priya,

I want trigger to count all the orders of particular customer and need to update in Account and Case field

Thank You

 

trigger NumberOfChild on Order(After Insert,After Update,After Delete) {
List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
    if(Trigger.isInsert){
         if(trigger.isAfter){
        for(Order con : Trigger.new){
            if(con.AccountId != null){
            setAccIds.add(con.AccountId);
                }
            }
        }
    } 
    system.debug('setAccIds ==> '+setAccIds);
    if(Trigger.isUpdate){
         if(trigger.isAfter){
        for(Order con : Trigger.new){ 
            if(con.AccountId!=Trigger.oldMap.get(con.Id).AccountId){
                   setAccIds.add(con.AccountId);
                setAccIds.add(Trigger.oldMap.get(con.Id).AccountId);
                }
          
            }        
        }
    }
    if(Trigger.isDelete){
        if(trigger.isAfter){
        for(Order con : Trigger.old) { 
            if(con.AccountId != null){
            setAccIds.add(con.AccountId);
                }
            }
        }
    }    
    for(Account acc :[Select id,Total_Orders__c ,(Select id,name from Orders) from Account where Id in : setAccIds]){
        acc.Total_Orders__c = acc.Orders.size();
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList;     
    }
}

 

I tried with this code but it  updated only Account field not case field