Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trigger InvoiceLineItemTrigger on Invoice_Line_Item__c (after insert, after update, after delete, after undelete) {
- // Get the parent Invoice Ids.
- Set<Id> invoiceIds = new Set<Id>();
- for (Invoice_Line_Item__c lineItem : Trigger.new) {
- // Add the Invoice Id from each Line Item to the list
- invoiceIds.add(lineItem.Invoice__c);
- }
- // Map to relate parent Invoice Id to the Amount roll-up value from all child Invoice Line Item records
- // The first time we see the Invoice, we will make the map entry
- // Next time we will add the Amount to the existing value
- Map<Id, Decimal> invoiceToAmountMap = new Map<Id, Decimal>();
- for (Invoice_Line_Item__c lineItem : [SELECT Id, Invoice__c, Amount__c
- FROM Invoice_Line_Item__c
- WHERE Invoice__c IN :invoiceIds]) {
- Decimal newInvoiceAmount = lineItem.Amount__c;
- // If the map already has a value for this Invoice, add that to this amount
- if (existingInvoiceAmount.containsKey(lineItem.Invoice__c)) {
- Decimal existingMapValue = invoiceToAmountMap.get(lineItem.Invoice__c);
- newInvoiceAmount = newInvoiceAmount + existingInvoiceAmount;
- }
- // Now put the new amount into the map
- invoiceToAmountMap.put(lineItem.Invoice__c, newInvoiceAmount);
- }
- // List to put the Invoice records that need their Amount__c roll-up updated
- List<Invoice__c> invoicesToUpdate = new List<Invoice__c>();
- // Now we will make the Invoice records to update
- for (Id invoiceId : invoiceToAmountMap.keySet()) {
- Decimal invoiceAmount = invoiceToAmountMap.get(invoiceId);
- Invoice__c tempInvoice = new Invoice__c(
- Id = invoiceId,
- Amount__c = invoiceAmount
- );
- invoicesToUpdate.add(tempInvoice);
- }
- // update the invoices
- update invoicesToUpdate;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement