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
Somasundaram S 1Somasundaram S 1 

how to get sum from child object from parent in lookup relation

I have a reuiqrement i want to have a field in parent record and get the sum of a field from all child record. this is lookup relationship record. how to do in a easy way , please suggest me.
Best Answer chosen by Somasundaram S 1
ManojjenaManojjena
Hi Somasundaram ,

You have to write a trigger in child object and trigger will do the job .
Please check below link where I have added a post for same kind of requirment .Where you need to replace object and field name accordigngly so that it will work for you .

https://developer.salesforce.com/forums/ForumsMain?id=9060G000000UZq8QAG

Let me know incase it solve your problem .

Thanks
Manoj
 

All Answers

ManojjenaManojjena
Hi Somasundaram ,

You have to write a trigger in child object and trigger will do the job .
Please check below link where I have added a post for same kind of requirment .Where you need to replace object and field name accordigngly so that it will work for you .

https://developer.salesforce.com/forums/ForumsMain?id=9060G000000UZq8QAG

Let me know incase it solve your problem .

Thanks
Manoj
 
This was selected as the best answer
Somasundaram S 1Somasundaram S 1
Manoj 
         I will try trigger before that any other easy way to do it like using process builder , if i couldnt get any good suggetsion i will go trigger, if i get process builder i will do in production. 
thanks
soma
Somasundaram S 1Somasundaram S 1
01
trigger TotalPiecesSum   on OrderItem  ( after insert, after update,after delete,after undelete) {
02
     Set<Id> ordIdSet=new Set<Id>();
03
     List<Order> ordListToUpdate=new List<Order>();
04
     if(Trigger.isInsert || Trigger.isUndelete){
05
          for(OrderItem  ordItm : Trigger.new){
06
             if(ordItm.OrderId != null){
07
                ordIdSet.add(ordItm.OrderId);
08
             }     
09
          }
10
     }
11
     if(Trigger.isUpdate){
12
        for(OrderItem  ordItm : Trigger.new){
13
             if(ordItm.OrderId != null && ordItm.Pieces__c != trigger.oldMap.get(ordItm.Id).Pieces__c){
14
                ordIdSet.add(ordItm.OrderId);
15
             }     
16
         }
17
     }
18
     If(Trigger.isDelete){
19
        for(OrderItem  ordItm : Trigger.old){
20
            if(ordItm.OrderId != null){
21
                ordIdSet.add(ordItm.OrderId);
22
            }      
23
        }
24
    }
25
    if(!ordIdSet.isEmpty()){
26
        for(AggregateResult res : [SELECT OrderId,sum(Pieces__c)can FROM OrderItem  WHERE OrderId IN :ordIdSet GROUP BY OrderId]) {
27
            ordListToUpdate.add(new Order(Id=(Id)res.get('OrderId'),Total_Pieces1__c=(Double)res.get('can')));
28
        }
29
    }
30
    if(!ordListToUpdate.isEmpty()){
31
        try{
32
            update ordListToUpdate;
33
         }catch(DmlException de){
34
            System.debug(de);
35
         }
36
     }
37
}
Manoj 
          in your above code orderitem is child record right , where are you getting the id of parent record to update the sum of pieces, could you please advise me.
thanks
soma

 
ManojjenaManojjena
Yes Soma ,

Order is the parent object and orderItem is the child object Pices__c is the field in orderItem and  Total pices1__c is the field in Order wheer trigger is updating the value .

Let me know incase any  !!
Thanks
Manoj
Somasundaram S 1Somasundaram S 1
one very basic question where the id of child object is stored orderid? in my scenario my parent object is samplelot and child is sample transaction then the id will be samplelot.sampletransactionid is it right? or some thing differe , my apologies for this small query
Somasundaram S 1Somasundaram S 1
Manoj

Thanks for your help and patient i modified the code as per my need and i got below error when i update the existing quantity what am i missing pls suggest me 
"Apex trigger Totalquanityleft caused an unexpected exception, contact your administrator: Totalquanityleft: execution of AfterUpdate caused by: System.TypeException: Invalid id value for this SObject type: a0i0E0000000YDuQAM: Trigger.Totalquanityleft: line 31, column 1"


 
trigger Totalquanityleft   on Sample_Transaction__c( after insert, after update,after delete,after undelete) {
     Set<Id> transactionIdSet=new Set<Id>();
     List<Sample_Lot__c> ordListToUpdate=new List<Sample_Lot__c>();
     if(Trigger.isInsert || Trigger.isUndelete){
          for(Sample_Transaction__c qnty: Trigger.new){
             if(qnty.id != null){
                transactionIdSet.add(qnty.Id);
             }    
          }

     }

     if(Trigger.isUpdate){
        for(Sample_Transaction__c qnty: Trigger.new){
             if(qnty.id != null && qnty.Transaction_Quantity__c != trigger.oldMap.get(qnty.Id).Transaction_Quantity__c){
                 transactionIdSet.add(qnty.Id);
             }    
         }
     }
     If(Trigger.isDelete){
        for(Sample_Transaction__c qnty : Trigger.old){
            if(qnty.Id != null){
                 transactionIdSet.add(qnty.Id);
           }     
        }

   }

    if(!transactionIdSet.isEmpty()){
        for(AggregateResult res : [SELECT id,sum(Transaction_Quantity__c)can FROM Sample_Transaction__c  WHERE id IN :transactionIdSet GROUP BY id]) {
        ordListToUpdate.add(new Sample_Lot__c (Id=(Id)res.get('id'),Quantity_Left__c=(Double)res.get('can')));
        
           
        }
        
    }
    if(!ordListToUpdate.isEmpty()){
        try{
            update ordListToUpdate;
         }catch(DmlException de){
            System.debug(de);
         }



     }



}

 
Somasundaram S 1Somasundaram S 1
Manoj 
         could you please help me i couldnt get clue for the above error
ManojjenaManojjena
Hi Somasundaram ,

What is the error you are getting ?
Somasundaram S 1Somasundaram S 1
thanks for your quick reply am getting below error
"Apex trigger Totalquanityleft caused an unexpected exception, contact your administrator: Totalquanityleft: execution of AfterUpdate caused by: System.TypeException: Invalid id value for this SObject type: a0i0E0000000YDuQAM: Trigger.Totalquanityleft: line 31, column 1"
Somasundaram S 1Somasundaram S 1
am getting error here i am confused and couldnt get the parent object sample_lot__c in get('id') am not sure what to mention 
ordListToUpdate.add(new Sample_Lot__c (Id=(Id)res.get('id'),Quantity_Left__c=(Double)res.get('can')));
ManojjenaManojjena
Hi Somasundaram,
You have problem like Sample_Transaction__c  object there will be a look up field to  Sample_Lot__c you need to get that field in place Id you are updating   Sample_Lot__c with Sample_Transaction__c Id  .I think you are clear now .

let me know incase you have issue .

Thanks
Manoj
Somasundaram S 1Somasundaram S 1
Compile Error: Invalid type: Sample_Lot_ID__c at line 34 column 66 , some thing i am missing am learning this time what will be the issue Manoj
ordListToUpdate.add(new Sample_Lot__c (Sample_Lot_ID__c=(Sample_Lot_ID__c)res.get('id'),Quantity_Left__c=(Double)res.get('can')));
Somasundaram S 1Somasundaram S 1
I used below code and solved my issue thanks for your suggestion and patient Manoj
trigger quantityleft on Sample_Transaction__c (after insert,after update,after delete,after undelete) {
    List<Sample_Lot__c> list_Account= new List<Sample_Lot__c>();
    set<Id> set_Opportunity = new set<Id>();
     if(Trigger.isInsert || Trigger.isUndelete){
        for(Sample_Transaction__c objOpp: trigger.new){
        
        if(objOpp.Completed_Transaction__c == true){
         set_Opportunity.add(objOpp.Parent_id__c);
           }
    }
    }
    
    if(Trigger.isUpdate){
        for(Sample_Transaction__c objOpp: trigger.new){
        
        if(objOpp.Completed_Transaction__c == true){
         set_Opportunity.add(objOpp.Parent_id__c);
           }
  }
    
    
    }
    
    if(Trigger.isdelete){
        for(Sample_Transaction__c objOpp: trigger.old){
        
        if(objOpp.Completed_Transaction__c == true){
         set_Opportunity.add(objOpp.Parent_id__c);
           }
  
    }
    
    }

    if(!set_Opportunity.isEmpty()){
    
    
    
                 Decimal Sum;
       Sum=0;

  for(Sample_Transaction__c sample_transaction : [SELECT id,Sample_Lot_ID__c, Transaction_Quantity__c FROM Sample_Transaction__c WHERE Parent_id__c = : set_Opportunity

]){
            
            Sum+= sample_transaction.Transaction_Quantity__c;
  
    
    for(Sample_Lot__c objAccount : [SELECT Id, Quantity_Left__c FROM Sample_Lot__c WHERE Id = : sample_transaction.Sample_Lot_ID__c]){

 

            objAccount.Quantity_left__c = Sum ;

            list_Account.add(objAccount);

 update objAccount ;

        }
        
 }
}

    
}