You need to sign in to do that
Don't have an account?
SImmy
Can anyone please explain while working with related objects when should we use before trigger and when to go for after trigger?
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; } }
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
All Answers
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
Rule of thumb should be that:
1. if you are validating or working with your record, then the before trigger would be preferred.
2. if you are updating related records, then you should be using the after trigger.
Part of the reason would be if we consider the Order of Execution.
in part / in short
...
Before Triggers
Field validation including user defined validation
Duplicate check
After triggers
...
In the sample code above, consider what would happen if you were to have validation that prevents the save after the before trigger runs and then the user discards the changes. Your related record has been updated , and yet the changes to the original record have been discarded.
Whilst your trigger would work as expected, I have found that you cannot rely on the end-user to always do things the way you expect them.
Regards
Andrew