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
Haider NaseemHaider Naseem 

Trigger Read Only Exception not encountered. Why?

Hi,

I have the following trigger:
trigger conCreateFromAccount on Account (after insert) {
  List<Contact> conList = new List<Contact>();
      for (Account newAccount: Trigger.New) {

           Contact con = new Contact();
           con.lastname = newAccount.name + '  - Contact';
           con.Accountid = newAccount.id;
           conList.add(con);
          }
          
    insert conList;
    list<account>acctsUp = new list<account>();
    for(contact e: conList){

         account a = new account(Id = e.AccountId);
         a.Contact_ID__c = e.Id;
         acctsUp.add(a);
      }

      update acctsUp;
}

From what I know, records in AFTER are read-only and cannot be updated. However, I am able to update the account record in the after insert trigger without any issue. Theoretically I should be receiving the Read Only error, but I am not. Why?
 
Best Answer chosen by Haider Naseem
Narender Singh(Nads)Narender Singh(Nads)
Hi Haider,

In a after insert trigger it is not allowed change field using trigger.new. This is the right and complete statement.

In your code if you had used soemthing like this then you will get the read-only error.
for(account a:trigger.new){
 //Updating a account field value
}

Let me know if you have any doubts.
Thanks!

All Answers

Narender Singh(Nads)Narender Singh(Nads)
Hi Haider,

In a after insert trigger it is not allowed change field using trigger.new. This is the right and complete statement.

In your code if you had used soemthing like this then you will get the read-only error.
for(account a:trigger.new){
 //Updating a account field value
}

Let me know if you have any doubts.
Thanks!
This was selected as the best answer
imrohitimrohit
Hi Haider 
because you are not updating any account in the below for loop you are not getting 'Read only exception' 
for (Account newAccount: Trigger.New) {

           Contact con = new Contact();
           con.lastname = newAccount.name + '  - Contact';
           con.Accountid = newAccount.id;
           conList.add(con);
          }
but if you do something like this you will get   'Read only exception' 
list<account>acctsUp1 = new list<account>();
      for (Account newAccount: Trigger.New) {

           Contact con = new Contact();
           con.lastname = newAccount.name + '  - Contact';
           con.Accountid = newAccount.id;
           conList.add(con);
           newAccount.name='testName';
           acctsUp1.add(newAccount);
          }
          update acctsUp1;