You need to sign in to do that
Don't have an account?
gweston
read only error on Apex trigger
I am trying to create a simple trigger that check is a field has updated and if so adds a datetime stamp in another field.
I am getting a read only error and I know it is because I am trying to update the trigger.old. The problem is I am new and do not know how to update the trigger.new. I assume you are supposed t switch back but I can not figure out how to do it
Here is my code so far
trigger CreateDispositionTimeStamp on Lead (after insert, after update) { for (Lead l : System.Trigger.new){ Lead beforeUpdate = System.Trigger.oldMap.get(l.Id); if(l.Status != beforeUpdate.Status){ l.Last_Disposition_Update__c=datetime.now(); } } }
Any help would be appreciated.
Use this trigger instead
Changes in this trigger,
After trigger changed to before : You don't need to use after as after trigger is mainly used to update any other object not the object that you are writting trigger for. this change will by default sove your problem as trigger.naw is not writable on after trigger but it is writable on before trigger.
I hope this will help you, please ask if any issue comes.
All Answers
You want to use a before trigger, in after triggers updates to the values in trigger.new aren't allowed directly.
In general if you're updating another field on the triggering object, use a before trigger. If you're updating another object use an after trigger. Before triggers represent all the changes to the triggering object before it hits the database, after has all of the changes once it hits the database (e.g. lastModifiedDate gets update, Ids are assigned). For instance if you wanted to created a child record for a lead automatically, you need the lead id, which isn't available until after the lead has been put into the database.
Use this trigger instead
Changes in this trigger,
After trigger changed to before : You don't need to use after as after trigger is mainly used to update any other object not the object that you are writting trigger for. this change will by default sove your problem as trigger.naw is not writable on after trigger but it is writable on before trigger.
I hope this will help you, please ask if any issue comes.
Hi gweston,
Trigger by shashikant should work, if doesn't then give this a try:
Thank you all for your help and advice. I really appreciate it!
G