You need to sign in to do that
Don't have an account?
David_
Best Practices for resolving "System.FinalException: Record is read-only"
Hey there,
the System.FinalException: Record is read-only error is a well known error when talking about After Insert Triggers. I was wondering what's the most common workaround to resolve it.
Example scenario:
Let's say we want to write an After Insert Trigger that...
1) ... sets a field value in a newly created Lead record
2) ... creates a related record (e.g. Task) and therefore requires the Record Id of the new Lead (this part of the logic actually forces us to go for an After Trigger).
This code apparently will give us the notorious error message:
What's the most used technique to get out of this dilemma? How should the above code be amended?
Best,
David
the System.FinalException: Record is read-only error is a well known error when talking about After Insert Triggers. I was wondering what's the most common workaround to resolve it.
Example scenario:
Let's say we want to write an After Insert Trigger that...
1) ... sets a field value in a newly created Lead record
2) ... creates a related record (e.g. Task) and therefore requires the Record Id of the new Lead (this part of the logic actually forces us to go for an After Trigger).
This code apparently will give us the notorious error message:
trigger leadTestTrigger on Lead (after insert) { for (Lead myLead : Trigger.new) { // We're inserting a value into a field of the initial record myLead.AnyField = 'Any Value'; // Create a task related to the Lead Task myTask = new Task(); myTask.Subject = 'Anything'; myTask.WhoId = myLead.Id; myTask.Priority = 'Normal'; myTask.Status = 'Not Started'; insert myTask; } }
What's the most used technique to get out of this dilemma? How should the above code be amended?
Best,
David
For the above stated scenario, you will have to use both, before and after triggers.
1) ... sets a field value in a newly created Lead record ---- Before Insert
2) ... creates a related record (e.g. Task) and therefore requires the Record Id of the new Lead (this part of the logic actually forces us to go for an After Trigger). -- After Insert
Use below snippet for your reference:
Please like and mark as resolved, if this helps.
All Answers
For the above stated scenario, you will have to use both, before and after triggers.
1) ... sets a field value in a newly created Lead record ---- Before Insert
2) ... creates a related record (e.g. Task) and therefore requires the Record Id of the new Lead (this part of the logic actually forces us to go for an After Trigger). -- After Insert
Use below snippet for your reference:
Please like and mark as resolved, if this helps.
Try this code:
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi