3

I am trying to create a Simple Apex Trigger that performs an update to the custom "Chargent Order" record whenever one is created or edited. I want it to look through a relationship field "Finacial Statement" and grab a few fields from it and then update them down to the Chargent Order that started the Trigger.

I am not receiving any errors but the fields simply are not updating. I am probably missing something very simple that I am just not seeing any help would be appreciated. My code is below:

trigger ChargentOrderPopulateACHInformation on ChargentOrders__ChargentOrder__c (before insert, before update) {

    for(ChargentOrders__ChargentOrder__c co : 
        [SELECT ChargentOrders__Bank_Account_Number__c, 
                ChargentOrders__Bank_Routing_Number__c, 
                ChargentOrders__Bank_Account_Type__c, 
                Financial_Statement__r.ACHAccountType__c, 
                Financial_Statement__r.ACH_Account_Number__c, 
                Financial_Statement__r.ACHRoutingNumber__c 
         FROM ChargentOrders__ChargentOrder__c WHERE Id IN: Trigger.new]){

                 co.ChargentOrders__Bank_Account_Number__c = co.Financial_Statement__r.ACH_Account_Number__c;
                 co.ChargentOrders__Bank_Routing_Number__c = co.Financial_Statement__r.ACHRoutingNumber__c;
                 co.ChargentOrders__Bank_Account_Type__c = co.Financial_Statement__r.ACHAccountType__c;

        }
}

1 Answer 1

3

The free record update that you get with before insert and before update triggers only works if you modify the instances of the records that are stored in trigger.new or trigger.newmap

Performing a query creates separate in-memory instances of those records.

You'll need to iterate over trigger.new directly for this to work.
You'll still want to perform your query outside of your loop using WHERE Id IN :trigger.new.

The last thing to be aware of is that your query won't return any records in before insert, because your records aren't inserted into the database until just before the after insert trigger event is fired.

2
  • I tried using After instead of Before and that threw some errors. I also did not think I needed to use after seeing as I do not need the Record ID of the new record. All I am doing is updating some fields on the record as it is being created. I do not fully understand your suggestions. Would you mind modifying my code about to help me understand what you are getting at? Thanks Commented Mar 6, 2019 at 19:07
  • I went back and spent some more time looking into this and was able to get it resolved. Thanks so much for the help. Commented Mar 6, 2019 at 21:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .