+ Start a Discussion
defray userdefray user 

getting wrong value in trigger !!

trigger emiTrigger on EMI_Payment__c (after insert) {
Set<id> loanid = new Set<id>();
List<Loans__c> loanslist = new List<Loans__c>();
for(EMI_Payment__c e : Trigger.new){
   loanid.add(e.Loan_Id__c);
}
for(Loans__c loan : [select id,Name,EMI__c,paid_amount__c,(select id,amount__c from EMI_Payment__r) from Loans__c where id IN : loanid]){
   for(EMI_Payment__c e:loan.EMI_Payment__r){
         //ading Emi amount to old paid amount , its giving worng value
         loan.paid_amount__c = loan.paid_amount__c +e.amount__c;
         system.debug('updated for...'+loan.paid_amount__c+'...>'+ e.amount__c);
   }
   loanslist.add(loan);
}
update loanslist;
system.debug('updated ...');
}

==================================================
Loans__c  ==> parent object
EMI_Payment__c  ==> child object
trying to update   loan.paid_amount__c with new EMI payment amount but its coming up with wrong value but if I debug for same value its showing correct in logs

Example : Assume 45281 is a initial value of loan.paid_amount__c 
and next if I give 45281 as input  for e.amount__c
expected to happen -
loan.paid_amount__c = loan.paid_amount__c +e.amount__c;
45281 = 45281 + 45281; ==> 96502
but its coming up with ==> 144,753


I am not understanding why ?
 
Best Answer chosen by defray user
Anthony McDougaldAnthony McDougald
Good Evening defray,
Hope that your day is off to an amazing start. We've edited your code with the help of resources below. This is under the assumption that the API name for the lookup field of Loans is Loans__c. Please test and report back when you get the chance. Hope this helps and may God bless you abundantly.
Resource (https://salesforce.stackexchange.com/questions/23338/trigger-to-update-parent-object-value-with-child-value)
trigger emiTrigger on EMI_Payment__c (after insert) { 
  Map<ID, Loans__c> parentLoans = new Map<ID, Loans__c>(); 
  List<Id> listIds = new List<Id>();

  for (EMI_Payment__c e : Trigger.new {
    listIds.add(e.Loan_Id__c);
  }


  parentLoans = new Map<Id, Loans__c>([SELECT id, paid_amount__c,(SELECT ID, amount__c FROM EMI_Payment__r) FROM Loans__c WHERE ID IN :listIds]);

  for (EMI_Payment__c e: Trigger:new){
     Loans__c myLoan = parentLoans.get(e.Loan_Id__c);
     myLoan.paid_amount__c += e.amount__c;
  }

  update parentLoans.values();
}


Best Regards,
Anthony McDougald