+ Start a Discussion
Adriana ReyesAdriana Reyes 

Trigger on child record to update parent record help

I have an invoice payment child object related to the parent invoice object. I created a trigger on the child, that updates the payment date on the invoice when the full payment is posted. There is a status formula field on the invoice that updates to "PAID" when the balance on the invoice is equal to zero. It doesn't get updated to "PAID" until after the invoice payment record is saved so I think that is causing my trigger to not work and update the payment field. Does anyone have any suggestions on how I can go about this? Thanks!
 
trigger Update_Payment_Date on gii__ARInvoicePayment__c (after insert, after update) {
    List<gii__OrderInvoice__c>lstInvoiceToUpdate = new List<gii__OrderInvoice__c>();
    Map<Id,gii__OrderInvoice__c>invoiceMP;
    
    for(gii__ARInvoicePayment__c pmt:trigger.new)
    {
        if (pmt.gii__PaymentDate__c != null && pmt.Invoice_Status__c == 'PAID')
        {
            lstInvoiceToUpdate.add(new gii__OrderInvoice__c(Id = pmt.gii__Invoice__c, Paid_Date__c = pmt.gii__PaymentDate__c, gii__PaymentDate__c = pmt.gii__PaymentDate__c));
        }
    }
    update lstInvoiceToUpdate;
}

 
NagendraNagendra (Salesforce Developers) 
Hi Adriana,

Based on your description of the data model, this is an order of execution issue.

Your child-object trigger goes off at Step 7 of the save process for the child objects.

Executes all after triggers.

At that point, roll-up summary fields on the parent have not yet been updated, because that change doesn't take place until Step 16:
If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through the save procedure.

In Step 16, we recurse to parent-object update triggers if the roll-up summary field is updated, but it's too late for your child-object triggers to react to the update - they've already run, and already seen data on the parent that's before the update to roll-up summary fields.

Solution: move this logic to a parent-object trigger. It sounds like what you need to do is, when the balance goes to zero, query for payments related to the invoice and populate the payment date fields with the latest payment date (or simply today's date, if that meets your requirements).

Thanks,
Nagendra