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
jagdish nikam 9jagdish nikam 9 

Updation in before trigger

Hi All,

I am new to the salesforce and wanted to clarify some basic concept. Please find below code

trigger CreateAccount on Account (before insert){
    for(account a :{
         a.industry = 'Transportation';
I just wanted to confirm that once your iteration control come at end of for loop at that time new account(which is in context) is get created with industry type Transportation and get commited. This created record is now read only and if we write update statment outside for loop then it means we are trying to update read only record and it gives an error message.

Is my understanding correct?  

Hi Jagdish,

The concept behind records in context being read only is during the after update/insert trigger events. A runtime error is thrown when context records are updated due to the fact 'these' records are read only. Its perfectly safe to update records in the before update trigger event.
In the above example, we are in the before insert trigger context and as such the record isn't created yet. You should be able to change the fields here. The created record is 'not' read only as its still in the 'before insert' context.
The error message shall come in to effect when you do the same operation in the after update context because as the event name suggests, after update trigger fires 'after the record has been updated in the database' and as such all such records are read only. You will get an error if you try to update fields directly in after update trigger.

As you titled your question to be conceptual understanding - let me tell you that you can update fields in after update triggers as well (but this is bad design, please remember that)... confusing? I know.. :)..
This is possible only when you freshly query such records from the database without depending on the context. As its a freshly queried record, you are out of the context. 

Hope the above makes sense. Please let me know for more queries. If not, please mark this as the answer. :)
Lokesh KumarLokesh Kumar
Hi Jagdish,

For more knowledge please have a look in the below article.

Thanks !