+ Start a Discussion
Robert_forcedRobert_forced 

Trigger After insert read only error

 I'm new to trigger coding, and faced the following problem:

I have a field (Assigned_to__c) to update in the following way:

-if the field is empty fill it with the name the record was CreatedBy
-if not, no action is required

The code is:

 





 
trigger AssignedToUpdate on TimeSheet__c (after insert, after update) {
for(Timesheet__c ts:Trigger.new){
if(ts.Assigned_to__c == null){
ts.Assigned_to__c = ts.CreatedById;
}
}
}


The problem is, that the "after insert" function is not working, the error code is:" The record is Read only".

 

I tried with "Before insert" but, of course before inserting the value of the CreatedBy field, it returns with null.

 

Any ideas would be appreciated!

Best Answer chosen by Admin (Salesforce Developers) 
SteveBowerSteveBower

Hi, If the goal is to fill that field with the ID of the User doing the insert, can you use a "before insert" and instead of using CreatedById (which hasn't been loaded yet), use UserInfo.GetUserId()?  (Or if you wanted the Text name, there are other methods on USerInfo).

 

If you *needed* to use CreatedById for some reason, you could change your After Insert trigger to build a new List of records which need updating.  Issue the Update (which would recursivly call the trigger's (after update function) which you'd need to stop after the first call).  

 

I'd explore the UserInfo option.  :-)   Best, Steve.

 

Also, offhand thought before hitting return... can you accomplish this with a Workflow rule and Field update instead of a trigger?

All Answers

SteveBowerSteveBower

Hi, If the goal is to fill that field with the ID of the User doing the insert, can you use a "before insert" and instead of using CreatedById (which hasn't been loaded yet), use UserInfo.GetUserId()?  (Or if you wanted the Text name, there are other methods on USerInfo).

 

If you *needed* to use CreatedById for some reason, you could change your After Insert trigger to build a new List of records which need updating.  Issue the Update (which would recursivly call the trigger's (after update function) which you'd need to stop after the first call).  

 

I'd explore the UserInfo option.  :-)   Best, Steve.

 

Also, offhand thought before hitting return... can you accomplish this with a Workflow rule and Field update instead of a trigger?

This was selected as the best answer
Robert_forcedRobert_forced

Hello Steve!

 

Thank you very much for your help, the Userinfo.GetUserId with before insert solved the case!

By the way, my first try was with workflow rule, but this function can not be done, because you can't give dynamic values to a lookup field.(In my case the Creator / User)