Skip to main content

I have had always studied that when working with related object we need to go for after trigger and if we are working with the same object then we need to go for before trigger or for performing validation checks.. please help me because today I tried one scenario and it's working for both before and after trigger. The code is below: 

trigger UpdateAccountField on Contact (before insert, before update) {

Set <String> accID = New Set <String> ();

For (Contact con: Trigger.new) {

if (con.AccountId != Null ) {

accID.add (con.AccountId);

}

}

If (accID.size ()> 0) {

List <Account> upAccList = new List <Account> ();

For (Account ac: [SELECT Id, csrs__FieldUpdate__c FROM Account WHERE id in: AccID AND csrs__FieldUpdate__c != True]) {

ac.csrs__FieldUpdate__c = true;

UpAccList.add (ac);

}

If (upAccList.size ()> 0)

update upAccList;

}

}

2 个回答
  1. 2019年7月21日 01:43
    Hi SImmy

    There is not such mandatory rule that you will use after trigger for related objects. After trigger is used if you are fetching the ID of the record that caused the trigger to fire for post DML operation.

    Maximum trigger(90%-95%) run as before trigger. In your example you are not using contact record ID for any operations. So it will work fine.

    I think this might help you 😊

    Thanks

    Subodh