function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sushma PriyaSushma Priya 

Doubt in Apex Trigger



I am new to Apex and started learning it recently. While going through Apex Developer's Guide I found following:


If you update or delete a record in its before trigger, or delete a record in its after trigger, you will receive a runtime error. This includes both direct and indirect operations. For example, if you update account

A, and the before update trigger of account A inserts contact B, and the after insert trigger of contact B queries for account A and updates it using the DML update statement or database method, then you are indirectly updating account A in its before trigger, and you will receive a runtime error.


Can anyone please explain the above functionality with an example?


Also, please provide with a link which has Apex practice classes and triggers for beginners.


Thanks in advance,

Sushma Priya.



On the delete side, its basically saying that you can't delete a record that caused the trigger to fire.  I have had code to do exactly this in an earlier version of the API which allowed it.  A record was inserted into a staging table, and I would then process the record , update the main table and delete the record from the staging table all in a trigger.  I think one reason this was changed is that if you do this when a user has inserted a record via the UI, its not a particularly good experience.


WRT updating, this simply means that you can't execute a DML update statement on a record that caused the trigger to fire.  One particularly good reason to avoid this is that it stands a good chance of leading to recursive updates - a record is updated, the trigger fires and updates the record again, which causes the trigger to fire again etc.  


Here's a couple of blog posts on triggers. There's plenty more information in the Apex Developer's Guide, but these provide a good overview.


To put it in layman's terms, you can't manipulate the records that fired the trigger in the first place in a way that would prevent the parent action from occurring properly, unless it's something like using the addError() method.


Most of it is easy to think about, when you come across it. Like not being able to use trigger.old in "before insert" triggers.