You need to sign in to do that
Don't have an account?

Apex Trigger Error: Update Account
Hello,
I am new to dev work and learning Apex code. I wrote a trigger that prevents us from needing to create several workflow field updates. It evaluates a few variables on a record and returns the proper Account Type. In the IDE the code passed the syntax check but when I went to try it out on an Account Record in the sandbox my trigger threw an exception as follows:
Error: Invalid Data.
Review all error messages below to correct your data. Apex trigger AccountTypeUpdate caused an unexpected exception, contact your administrator: AccountTypeUpdate: execution of AfterUpdate caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.AccountTypeUpdate: line 16, column 1
What can I do to fix this error? Here is the trigger code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | trigger AccountTypeUpdate on Account (after update) { |
You can't use DML (insert, update, etc) on trigger.new in an after update trigger. That only works in a before update trigger.
You need to re-query for your data (i.e. into a list or set) and then use DML on that list / set.
All Answers
You can't use DML (insert, update, etc) on trigger.new in an after update trigger. That only works in a before update trigger.
You need to re-query for your data (i.e. into a list or set) and then use DML on that list / set.
Thank you. I changed the trigger to a Before Update but the last part of your suggestion I'm not quite understanding. What do you mean by requery the data?
You need to execute SOQL to pull the data from the database.
Here is an example:
now you can loop thru AccountsToUpdate like you were trying to do with trigger.new and after doing your updates in the loop, add some DML to update the AccountsToUpdate List.
Thanks colemab. That makes sense. I'll give it a shot.