I would like to do understand the following trigger execution.

trigger MerchandiseTrigger on Merchandise__c (before insert) {

        Merchandise__c[] m = Trigger.new;
        for(Merchandise__c mer : m)
            if( mer.Uninventoried_Qty__c == null)
                mer.Uninventoried_Qty__c = mer.Total_Merchandise_QtyTotal_Qty__c;
            System.debug('Uninventoried : '+mer.Uninventoried_Qty__c);

This trigger's logic is working as expected i.e sets the "Uninventoried_Qty__c" with "Total_Merchandise_QtyTotal_Qty__c" if "Uninventoried_Qty__c" is not given while record creation.

Taking a step back and eye balling I can see following happening

a) I am creating a collection ("m") that contains the record(s) that will be processed because of this trigger event.

b) For each record("mer") in the collection ("m") I am applying the logic.

c) Then how this collection ("m") becomes the records causing the trigger event ?

I am guessing that it is because the collection "m" contains the memory address as it is complex data type and any changes that I make on this collection will in turn make the changes on the actual records.

Am I right ?

If not can someone please explain how the changes I make in "m" collection and gets propagated to the actual records in trigger.new ?


I think you've got a pretty good understanding of how things are flowing in that trigger. When you set up a trigger as "Before Insert", Salesforce will essentially "catch" the records on the way to the database, and give your trigger code a chance to work with them. When you enter the trigger, the special syntax "Trigger.new" returns a reference to those new Merchandise__c records that have not been written to the database yet. You can use this reference to make modifications to those records. Once this trigger finishes running, the records, (with any modifications that you've made), will then be written to the database.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.