0
votes

I am in the early stages of learning Apex and trying to write some code for a particular scenario. I have two custom objects called Outstanding and Transaction that are both children of an Account. I want to write a trigger that updates the end date of the Outstanding record that has a start date >= the start date on the Transaction and an end date < the end date on the Transaction. I want the end date on the correct Outstanding record to change to the end date on the Transaction.

Example:

Transaction: Start_Date__c (is changed to)= 1/2/2019 End_Date__c=1/31/2020

Outstanding Records:

  1. Start_Date__c 1/4/2018 End_Date__c 1/4/2019
  2. Start_Date__c 1/4/2019 End_Date__c 1/4/2020
  3. Start_Date__c 1/4/2020 End_Date__c 1/4/2021

When the Transaction's start date is changed to 1/2/2019, I want the trigger to find the relevant Outstanding record 2 and update the end date to 12/31/2019.

Hopefully, that makes sense. If it doesn't, please let me know and I'll try to explain it again. Any help would be appreciated. Thanks.

1
What have you tried? Where are you stuck? If you need help getting started, Trailhead has a good introductory module. - David Reed

1 Answers

0
votes
You have to write a trigger on your Transaction Object on after update context. Please try the below codes.
**Trigger** : 
`trigger TransactionTrigger on Transaction__c (after update) {
    Map<Id,Transaction__c> accTraMap = new Map<Id,Transaction__c>();
    for(Transaction__c transac : trigger.new){
        accTraMap.put(transac.Account__c, transac);
    }
    if(!accTraMap.isEmpty()){
        TransactionTriggerHandler.afterUpdate(accTraMap);
    }
}`
**Class :**

    public class TransactionTriggerHandler {
    public static void afterUpdate(Map<Id,Transaction__c> accTransMap){
        list<Outstanding__c> outstanding = [SELECT Id, Name, StartDate__c, EndDate__c, Account__c 
                                 FROM Outstanding__c where Account__c in:accTransMap.keyset()];

        list<Outstanding__c> outstandingToUpdate = new list<Outstanding__c>();

        for(Outstanding__c o : outstanding){
            if(accTransMap.containsKey(o.Account__c)){
                if(o.StartDate__c >= accTransMap.get(o.Account__c).Start_Date__c && o.EndDate__c < accTransMap.get(o.Account__c).End_Date__c){
                  o.EndDate__c = o.EndDate__c.toStartOfMonth().addDays(-1);
                    outstandingToUpdate.add(o);
                }
            }
        }
        system.debug('\n updated outstanding '+outstandingToUpdate);
        if(!outstandingToUpdate.isEmpty()){
            update outstandingToUpdate;
        }
    }
}