Apex, Development

Five things that rocked my world learning Apex

Ok maybe not rocked my world but when I started developing on the Salesforce platform I was very much figuring it out as I went along (If only trailhead existed then!). Unfortunately, there were some things that I wished I had known before I had started. In some cases meant I had to do rework or in worse cases didn’t even know I’d made a fundamental error. So here are the top things that “rocked my world” when developing Apex for the first time.

Triggers don’t fire all the time

When I was first introduced to triggers, I was told they were very much like database triggers. Every time a record was inserted, updated, deleted or undeleted the trigger would fire. I expected that after I had written my update & delete triggers on say the contact object, the trigger would always fire in the same way a database stored procedure trigger would fire. But this is not the case. There are a couple of scenarios where triggers are not fired. A full list is here but here are the ones I know caught me out:

  1. Cascading delete operations; If you have records in a master-detail relationship and someone deletes the parent record, the children will cascade delete. The kicker? Only the parent records delete trigger is fired, not the children. To protect yourself from this happening you can put logic in the parents delete trigger.
  2. Cascading update operations as a result of a merge operation; If you merge two records together the “winning” record is kept, and the losing record is deleted. Any child records of the losing record are then “re-parented” with the winning record, but the update triggers on the child records are not fired. For example if you had two account records that you were merging, and both had opportunities on them, the Account field on the losing account’s opportunities will be updated with the new/winning account (the “re-parenting”), but the update triggers won’t fire on those opportunity records.

Read more