I have two objects (A and B) in a many to many relationship, and when a field is updated in record X (obj A) that is related to y (obj b), I need to get all records that are related to y in order to update them too, I'm in a before trigger context because I first need to update record X and then update the other records that are not processed on the trigger, is this possible in a before trigger? Thank you!!
It's possible in a before trigger, but not recommended.
The benefit of using a before trigger is that you're able to make updates to the records being triggered (i.e. the instances of the records in
trigger.newMap) without the need for DML.
If you're updating other records (on the same object, or on another object), then that's when it's more appropriate to use an
Separating the two bits of work may initially seem like a waste of time, but it can make testing easier and being disciplined and sticking to a convention will help you (and others) later in time.
One big thing that you need to think about and take measures to prevent when you update records in an update trigger is recursion. It can be surprisingly easy for you to get yourself into an infinite loop. Record A causes record B to be updated, which causes record A to be updated again. Records A and B could be on the same object, or on different objects.
Some simple, general advice to avoid such situations:
- Try to stick to one method of automation per object (use a trigger, flow, or process builder, and try to stick to only one of them) to make it easier to keep track of what work is being done
- Use, at the very least, a
static Set<Id>to keep track of record Ids that you've already worked on (gives you a way to prevent work from being done again in a given transaction, and won't cause issues when you work on > 200 records at a time like a
static Booleanrecursion prevention method would)
- Try to keep updates flowing in a single direction (i.e. Parent record update -> child records update). Things get messy very quickly if you have a parent record update child records which then update parent records again. Rollup summary fields make information flow from child records to their parent record (and cause the parent record to undergo an update of its own). Formula fields are a good way to pull information from a parent record without using code (and without causing an update)