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
m 3m 3 

i have a requirement, i have an object there is a related object to that (abc and child xyz)

i have a requirement, i have an object there is a related object to that (abc and child xyz) there is a numeric field on xyz (child object) if there is 5 record, i want to the total of 5 record in the parent record.  how do provide the functionality
 
 
NagendraNagendra (Salesforce Developers) 
Hi,

May I suggest you please find the pseudo code which is optimized with a similar requirement, just change the field names and the object names which should probably do the trick.
trigger TotalPiecesSum   on OrderItem  ( after insert, after update,after delete,after undelete) {
	 Set<Id> ordIdSet=new Set<Id>();
	 List<Order> ordListToUpdate=new List<Order>();
	 if(Trigger.isInsert || Trigger.isUndelete){
		  for(OrderItem  ordItm : Trigger.new){
			 if(ordItm.OrderId != null){
				ordIdSet.add(ordItm.OrderId);
			 }		
		  }
	 }
	 if(Trigger.isUpdate){
	    for(OrderItem  ordItm : Trigger.new){
			 if(ordItm.OrderId != null && ordItm.Pieces__c != trigger.oldMap.get(ordItm.Id).Pieces__c){
				ordIdSet.add(ordItm.OrderId);
			 }		
		 }
	 }
	 If(Trigger.isDelete){
		for(OrderItem  ordItm : Trigger.old){
			if(ordItm.OrderId != null){
				ordIdSet.add(ordItm.OrderId); 
			}		
		}
	}
	if(!ordIdSet.isEmpty()){
		for(AggregateResult res : [SELECT OrderId,sum(Pieces__c)can FROM OrderItem  WHERE OrderId IN :ordIdSet GROUP BY OrderId]) {
			ordListToUpdate.add(new Order(Id=(Id)res.get('OrderId'),Total_Pieces1__c=(Double)res.get('can')));
		}
	}
	if(!ordListToUpdate.isEmpty()){
		try{
			update ordListToUpdate;
		 }catch(DmlException de){
			System.debug(de);
		 }
	 }
}
Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra