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
Swamy P R NSwamy P R N 

Trigger to Compare Total Child Values with Parent Value

Hi ,

In Parent Object (QUX_Forecast__c), i have Total Amount Field
In Child Object(Quota__c) , i have Amount Field
I am writing a trigger on Child Object for whenever a record is created or updated i need to compare parent value with all childs amount.
If  All childs amount is greater than parent Total Amount Field,i need to show a error message.
For this i wrote a code,but it is taking all child values along with current updated record.


trigger to_ShowError on Quota__c (before insert,before update) {

    set<Id> prntids = new set<Id>();
    for(Quota__c q:trigger.new){
        if(q.QUX_Forecast__c!=null){
            prntids.add(q.QUX_Forecast__c);
        }
    }
  
    Map<Id,QUX_Forecast__c> prntrecs= new Map<Id,QUX_Forecast__c>([select id,name,Time_Based_Mgmnt__c,Total_Amount__c
                                    from QUX_Forecast__c where id IN:prntids]);

     List<Quota__c> lreslts =[select q.id,q.Amount__c,q.QUX_Forecast__c from Quota__c q where (q.QUX_Forecast__c IN:prntids)];
      double childamnttotal;
      for(Quota__c a:lreslts){
          if(childamnttotal!=null){
              childamnttotal=double.valueof(a.Amount__c)+childamnttotal;
            
          }else {
              childamnttotal=double.valueof(a.Amount__c);
          }
      }
      for(Quota__c q:trigger.new){
         QUX_Forecast__c qfc = prntrecs.get(q.QUX_Forecast__c);
         if(qfc.Total_Amount__c!=null){
         system.Debug('Parent Amnt is '+qfc.Total_Amount__c);
         system.Debug('Total Child Amnt is '+childamnttotal);
             if(qfc.Total_Amount__c<childamnttotal){
                q.Amount__c.addError('You need to check with selected Parent Total Amount');
             }
         }
      }                            
}

I understood that , It is the issue with trigger.newmap.keyset() and oldmap.keyset() . if i use newmap.keyset() , iam not able to take current val for comparison.Please help me out with exact query and logic.
Ashish_SFDCAshish_SFDC
Hi Swamy, 


This question is similar to the other thread, https://developer.salesforce.com/forums/ForumsMain?id=906F00000009HYAIA2

Were you abel to solve this? 

Usually the first step would be enabling debug logs and checking the logs which have detailed errors and give us clues where the code breaks etc. 

If you have any further questions, reply back I will try my best to answer. 


Regards,
Ashish