When Should I Use Apex Triggers in Salesforce?
- When working with high data volume. Triggers can perform faster in such situations: if you’re getting process builder errors due to volume, consider using a trigger.[br][br]
- To control order of execution. If you have something in code and something in process builder and you need them to run in a specific order, use a trigger. [br][br]
- When everything else is in code already. When you’re forced to build out a complex coded process, it’s a best practice to consolidate your automations in code. Don’t create a rogue process builder here, because your developer won’t know what it’s doing.[br][br]
- If you need to fire before insert or on delete. (Note: this will change in a future release, which will have flows firing before inserts.)[br][br]
- When you have really complicated criteria, because Apex triggers can execute this much faster. It is possible to cripple your system with a CPU timeout error if you have a process builder dealing with too many operators (for example, we’ve seen this happen with too many “title contains” operators).[br]
What Do I Need to Know When Using Apex Triggers?
Avoid DIY code-hacking.
It can be tempting to copy/paste code from online sources into your Apex trigger, but this is not always advisable. If you’re doing so in a small Salesforce environment with a very simplistic use case, you can probably get away with it. But dropping DIY code into a more complex environment as a non-developer is risky, and can result in undeployable automation (even if it works in Sandbox).
Pay attention to trigger events.
It’s important to understand the event in which your code will run. A trigger framework can help you to be intelligent about this and ensure that your code runs at the right time. For example, it can detect whether your code should run before insert, after insert, before update, after update, before delete, or after delete.
Fire your trigger selectively.
Remember that no matter what, triggers always fire. You need to ensure that your criteria is as selective as possible. As always, avoid this issue by logically thinking through every possible outcome of your trigger and ensuring your criteria includes a field change event.
Remember that triggers fire synchronously.
Firing synchronously subjects Apex triggers to processing limits including CPU time query limits and row locking issues. Triggers should only be used if you must initiate a function in real time. (Stay tuned for an upcoming post where we explore asynchronous processes!)
[vcex_divider_dots color=”#66d7d1″ margin_top=”10″ margin_bottom=”10″]
What issues have you run into with Apex triggers? We’d love to hear from you!