+ Start a Discussion
Sourav PSourav P 

To sum up the amounts from related list as per certain criteria

Hi
In Contract object, i have the " Payments" as the related object.
In Payments i have the field " Opp renew check" where the values can be 01,02,03 etc. Multiples Payments records can have the value as 01 or 02 or 03 etc.
Now i want that, where its all say, 01, those all record's amount will sum up and show in the Contract object, when new records comes with 02, the latest( highest number) will get sum up.
E.g if two records with 01, and values as 1. $1000
                                                                  2. $500
Those two will sum up as $1500.

When new records come up with 02, say 1. $2000, 2. $ 400
It will change to $2400.

Both are relatd as Master-detail. I tried in trigger as below. But as new to apex, i think some issue with my below trigger, Can anyone plz suggest where i went wrong.
 
trigger paymentTrigger on Payments__c(After insert,after delete){
  List<Contract> conListToUpdate=new List<Contract>();
  Set<Id> conIdSet= new Set<Id>();
  if(Trigger.isAfter){
     if(Trigger.isInsert){
         for(Payments__c pay : trigger.new){
            if(pay.Opp_Renewal_Check__c!= null){
                conIdSet.add(pay.Paid_to_date_2__c);
            }
        }
     }
     if(Trigger.isDelete){
        for(Payments__c pay  : trigger.old){
            if(pay.Opp_Renewal_Check__c!= null){
                conIdSet.add(pay.Paid_to_date_2__c);
            }
        }
     }
  }
 
  if(!conIdSet.isEmpty()){
    List<AggregateResult> aggRes=[SELECT SUM(Id)adding ,Opp_Renewal_Check__c chk FROM Payments__c WHERE Opp_Renewal_Check__c IN : conIdSet AND MAX(Integer.valueOf(Opp_Renewal_Check__c)) Group By Opp_Renewal_Check__c];
    for(AggregateResult agg : aggRes){
      Contract con =new Contract(id=(Id)agg.get('chk'),Paid_to_date_2__c = (Decimal)agg.get('adding'));
        conListToUpdate.add(con);
    }
    if(!conListToUpdate.isEmpty()){
       try{
           update conListToUpdate;
       }catch(DmlException de ){
           System.debug(de.getMessage());
       }
    }
  }
}

Replace Task_Count__c with your Opportunity API field API

 
Best Answer chosen by Sourav P
HARSHIL U PARIKHHARSHIL U PARIKH
If above is the criteria you need then I hope the trigger below helps:
(Just change the obejcts to your obejcts and logic is there)
Parent Object: Contact
            Fields: Gorss_Amount_Total__c 
Child Object : Credit__c
            Fields: Value__c, Gross_Amount__c 

Requirement: Sumup only child records with highest-value in Value__c number field into  the parent.
(e.g. if Contact name is John Doe and he has 4 credit scores such as 
        Credit record -1 With Value__c = 1, Gross_Amount__c = 10,
        Credit record -2 With Value__c = 2, Gross_Amount__c = 5,
        Credit record -3 With Value__c = 3, Gross_Amount__c = 25,
        Credit record -4 With Value__c = 3, Gross_Amount__c = 75

At this point only two credit records needs to be summed up which are record -3 and record - 4 and Gorss_Amount_Total__c should be = 100.

Trigger Code:
Trigger CountingHighestValuesGrossAmount on Credit__c(After Insert, After Update, After Delete, After UnDelete){
    
    List<Id> conIds = New List<Id>();

    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
        For(Credit__c crd : Trigger.New){
            If(crd.Contact__c != null){
                conIds.add(crd.Contact__c);
            }
        }
    }
    If(Trigger.IsDelete){
        For(Credit__c crd : Trigger.Old){
            If(crd.Contact__c != null){
                conIds.add(crd.Contact__c);
            }
        }
    }
    
    List<Contact> listOfCons = New List<Contact>();
    Double HighestNum = 0.00;
    
    For(Contact Con: [Select Id, Gorss_Amount_Total__c, 
                                        (Select Id, Value__c, Gross_Amount__c FROM Credits__r ORDER BY Value__c DESC) 
                                            FROM Contact WHERE Id =:ConIds])
    {
       HighestNum = 0.00;
       Con.Gorss_Amount_Total__c = 0.00;
       List<Decimal> valuesList = New List<Double>();
       If(Con.Credits__r.size() > 0)
       {
           For(Credit__c c : Con.Credits__r)
           {
               valuesList.add(c.Value__c);              
           }
           HighestNum = valuesList[0];
       }
       //system.debug('The Size of valueList Is: ' + valuesList.size());
       //System.debug('HighestNumber Recoreded: ' + HighestNum );
       For(Credit__c EveryCredit : Con.Credits__r)
       {
           If(Integer.ValueOf(EveryCredit.Value__c) == HighestNum)
           {
               Con.Gorss_Amount_Total__c += EveryCredit.Gross_Amount__c;
           }
       }
       listOfCons.add(Con);
    }
    try{
        If(!listOfCons.IsEmpty()){
            update listOfCons;
        }
    }
    Catch(Exception e){
        System.debug('Thrown Exception for CountingHighestValuesGrossAmount Is:: ' + e.getMessage());
    }
    
    
}

Hope this helps!
 

All Answers

ManojSankaranManojSankaran
Hi Sourav,

I think we can acheieve this using roll up summary field.Below are the steps that you can follow to acheive you requirement.

1. Goto to the parent object (Master)
2. Create a Roll up Summary Field
3. In that we have an option to add condition (See my Screenshot below)
4. Create three fields as per your requirement. (for 01, 02 and 03)


Mark it as answer if it solves your query.
Thanks
Manoj

User-added image
ManojSankaranManojSankaran
Hi Sourav,
I think i Misunderstood the requirement. Let me try to correct your trigger.


Thanks
Manoj S
Sourav PSourav P
Hi Manoj, Thanks. Ya i cant create through roll up as, the Opp renew forllow up is keep changing, say, 01, next time 02, 03. etc. I want to take the max ones to sum up, one value say, 01 can have multiple records.
HARSHIL U PARIKHHARSHIL U PARIKH
Ok so help me understand a little..

You can have a multiple Payment records for one contract.
Every Payment record is going to have two fields in it. 1) Value, and 2) Opp Renew Check

This field named value can be 1000, or 2000 etc...
and Opp Renew Check has to be 01, or 02, or 03 etc.. correct ? I mean towards smaller to a larger number.

Now, let's say if you have 8 child records of Payment for ONE parent Contract
such as
Contract Name = My Contract
          Payment record - 1 = Opp Renew Check = 01, Value =  5000
          Payment record - 2 = Opp Renew Check = 01, Value =  2000
          Payment record - 3 = Opp Renew Check = 02, Value = 3000
          Payment record - 4 = Opp Renew Check = 02, Value = 10
          Payment record - 5 = Opp Renew Check = 02, Value = 20
          Payment record - 6 = Opp Renew Check = 02, Value = 50
          Payment record - 7 = Opp Renew Check = 03, Value = 900
          Payment record - 8 = Opp Renew Check = 03, Value = 900

So at this moment / stage, then Sum__c on Contract would be = 1800 correct?

 
HARSHIL U PARIKHHARSHIL U PARIKH
If above is the criteria you need then I hope the trigger below helps:
(Just change the obejcts to your obejcts and logic is there)
Parent Object: Contact
            Fields: Gorss_Amount_Total__c 
Child Object : Credit__c
            Fields: Value__c, Gross_Amount__c 

Requirement: Sumup only child records with highest-value in Value__c number field into  the parent.
(e.g. if Contact name is John Doe and he has 4 credit scores such as 
        Credit record -1 With Value__c = 1, Gross_Amount__c = 10,
        Credit record -2 With Value__c = 2, Gross_Amount__c = 5,
        Credit record -3 With Value__c = 3, Gross_Amount__c = 25,
        Credit record -4 With Value__c = 3, Gross_Amount__c = 75

At this point only two credit records needs to be summed up which are record -3 and record - 4 and Gorss_Amount_Total__c should be = 100.

Trigger Code:
Trigger CountingHighestValuesGrossAmount on Credit__c(After Insert, After Update, After Delete, After UnDelete){
    
    List<Id> conIds = New List<Id>();

    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUnDelete){
        For(Credit__c crd : Trigger.New){
            If(crd.Contact__c != null){
                conIds.add(crd.Contact__c);
            }
        }
    }
    If(Trigger.IsDelete){
        For(Credit__c crd : Trigger.Old){
            If(crd.Contact__c != null){
                conIds.add(crd.Contact__c);
            }
        }
    }
    
    List<Contact> listOfCons = New List<Contact>();
    Double HighestNum = 0.00;
    
    For(Contact Con: [Select Id, Gorss_Amount_Total__c, 
                                        (Select Id, Value__c, Gross_Amount__c FROM Credits__r ORDER BY Value__c DESC) 
                                            FROM Contact WHERE Id =:ConIds])
    {
       HighestNum = 0.00;
       Con.Gorss_Amount_Total__c = 0.00;
       List<Decimal> valuesList = New List<Double>();
       If(Con.Credits__r.size() > 0)
       {
           For(Credit__c c : Con.Credits__r)
           {
               valuesList.add(c.Value__c);              
           }
           HighestNum = valuesList[0];
       }
       //system.debug('The Size of valueList Is: ' + valuesList.size());
       //System.debug('HighestNumber Recoreded: ' + HighestNum );
       For(Credit__c EveryCredit : Con.Credits__r)
       {
           If(Integer.ValueOf(EveryCredit.Value__c) == HighestNum)
           {
               Con.Gorss_Amount_Total__c += EveryCredit.Gross_Amount__c;
           }
       }
       listOfCons.add(Con);
    }
    try{
        If(!listOfCons.IsEmpty()){
            update listOfCons;
        }
    }
    Catch(Exception e){
        System.debug('Thrown Exception for CountingHighestValuesGrossAmount Is:: ' + e.getMessage());
    }
    
    
}

Hope this helps!
 
This was selected as the best answer
Sourav PSourav P
Thanks a lot Govind, It worked.