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
Rajesh-InLoveWithSFdcRajesh-InLoveWithSFdc 

Trigger Execution Order Issue


HI All, I do not have much experience in Salesforce but i am learning and i came acroos this statement "You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown"

I have two issue now 
a)  As it is mentioned we can not update Object in After Trigger but we can update it like below 
trigger AccountNumberUpdate on Account (before insert,after insert) {
list<Account> up = new list<Account>();


for (Account c : Trigger.new)
{
if (Trigger.isBefore)
{
if (String.isBlank(c.AccountNumber))
{
 c.AccountNumber.addError('Account Number Can not be bLanks');
  
}}

if (Trigger.isAfter)

{
 Account a = [Select Id,AccountNumber from Account where id = :c.id];
 a.AccountNumber = NULL;
 up.add(a);

}
update up;
}

b) (Refre Above Code)Second issue with order of execution lets say i have custom validation on field here AccountNumber and in all after trigger again i am making AccountNumber blank in that  case error will not throw because custom validation does not takes place after trigger . Is it limitation of salesforce ?

Regards,
Rajesh 
Nayana KNayana K
As per your current code, exception will not be thrown from after trigger.

But if you just change one line i.e, 
trigger AccountNumberUpdate on Account (before insert,after insert) {

to
 
trigger AccountNumberUpdate on Account (before insert,after insert, before update) {

Then errr w​ill be thrown because,
update up;
will cause before update and after update to fire and control enters into before{} block of your code.
Rajesh-InLoveWithSFdcRajesh-InLoveWithSFdc
Hi Nayana, 
Thanks for your reply i understand the SoQL bukification and everything  i just need to know there is limitation in Trigger order of execution because after trigger no custom validation happens this i wanted to understand ! which is not happening currently in my code

Regards,
Rajesh  . 
shiv shankar 18shiv shankar 18
Hi Rajesh,

Please find the link below for the order of execution in salesforce.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm
http://www.asagarwal.com/2362/order-of-execution-rules-triggers-etc-in-salesforce-debug-log

Thanks 
Shiv Shankar
{tushar-sharma}{tushar-sharma}
Here we have a new addition here. We now have Before save flow which executes before triggers.
You can find updated details here: https://newstechnologystuff.com/2020/05/25/order-of-execution-in-salesforce/