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
Dnyanesh GawaliDnyanesh Gawali 

Custom rollup summary trigger problem

Hi,

I have created following trigger for custom rollup summary.
but now i want to calculate sum of all orderItem on insertion of each new OrderItem. Now it only adding new value into existing rollup field.

Object Details :
Parent : Order
Child : OrderItem
Roll up field : Total_Pieces1__c (order field)
Summurised field : Pieces__c (OrderItem field)

trigger TotalPiecesSum on OrderItem (before update, before insert,before delete) {

list<Order> a = new list<Order>();
    set<id> OrderIDs= new set<id>();

if(trigger.isInsert || trigger.isBefore){
   for(OrderItem o : Trigger.new){
      OrderIDs.add(o.Orderid);
   }
   }

else if(trigger.isDelete){
     for(OrderItem o : Trigger.old){
         OrderIDs.add(o.Orderid);
     }
}
else 
      
     if(trigger.isUpdate){
     for(orderItem o: trigger.new){
        if(trigger.oldmap.get(o.id).Order!=o.Order){
            OrderIDs.add(o.OrderID);
            OrderIDs.add(trigger.oldmap.get(o.id).OrderID);
        }
    }
}
    
    AggregateResult[] groupedResults = [SELECT SUM(Pieces__c),OrderId FROM OrderItem where OrderId IN :OrderIDs GROUP BY OrderId ];
    system.debug('*******groupedResults **********'+groupedResults);     
    
    for(AggregateResult ar:groupedResults) {
        Id orid = (ID)ar.get('OrderId');
        system.debug('*******selected Oredr id **********'+orid);     
        Decimal count = (Decimal)ar.get('expr0');
            
        Order o1 = new Order(Id=orid);
        o1.Total_Pieces1__c= count;
        system.debug('*******Total_Pieces1__cOredr id **********'+count); 
        a.add(o1);
       }
   update a;
}
VamsiVamsi
Update the trigger.isupdate section as below.
 
if(trigger.isUpdate)
{
     for(orderItem o: trigger.new){
        if(trigger.oldmap.get(o.id).Pieces__c != o.Pieces__c)
          {
            OrderIDs.add(o.OrderID);
  
           }
}
Please mark as best answers if the above heps ....!!!!
ManojjenaManojjena
Hi  Dnyanesh ,
Try with below code is bit more optimised .

 
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);
		 }
	 }
}

Let me know if it helps !!
Thanks 
manoj
Dnyanesh GawaliDnyanesh Gawali
Hello all, 

My Requirement: 
When total pieces are less than 720 then discount on total amount should be 20%. When total pieces are more than 720 then discount on total amount should be 35%

Whats Happening:  
1. When i added first product whose total pieces(240) are less than 720(As shown in image) it gives me total amount discounted by 20% i.e. 4660.80
2. Then i added another product which makes sum of total pieces(12) are less than 720 it also gives me total amount discounted by 20% i.e., 233.04
3. Now, Total pieces are 240 + 12 i.e, 252 and total amount is 4660.80 + 233.04 i.e., 4893.84
Till this step its calculating correct value.
4. I added again new product whose total pieces(600) i.e 852 which is greater than 720. Now as per my requirement total amount should be 3787.20 + 189.30 +9468. As when total number exceeded than 720 it should give me total amount discounted by 35% i.e., 13444.56 but its giving me a value 16,545.84. 

I tried code suggested by both of you but its working same.

User-added image


User-added image


User-added image

Thanks & Regards, 
Dnyanesh
Janno RipJanno Rip

Hello @Manojjena,

I had a similiar Use Case where your trigger was really helpful. I have still one tiny problem and that is with de-duplicating records. My parent record is the 'account' object and my child is 'index__c'. Now when I have several 'index__c' records on my account and I update 1 of them it all works fine. But when I have an account duplicate where each has an 'index__c' record and I merge those, I end up with two 'index__c' records on the lasting account but the trigger is not 'working'. It will not update my account based on the fields in my two 'index__c'. When I open the 'index__c' manually and change the values the trigger is firing. But I need it already after successful merge of two or more accounts.
 

I'm really not too deep into apex and trigger. I just used your code as a template and switched fiedls. Maybe you can help me out.

Thanks in Advance and Greetings

Jan