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
uzairuzair 

Getting error message 'Record is read-only'.

Hi All,

 

I'm writing a simple trigger to increment the value of a field.

 

trigger tgrCounter on Mileage__c (after insert, after update) {
	List MilToupdate = new List();
	for(Mileage__c Mlg : Trigger.new){
		Mlg.Counter__c = Mlg.Counter__c+1;
		MilToupdate.add(Mlg); 
	}
	update MilToupdate;
}

 

While saving the record i'm getting the following error message "Apex trigger tgrCounter caused an unexpected exception, contact your administrator: tgrCounter: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.tgrCounter: line 4, column 1"

 

Any help to over come this would be highly appreciated.

 

Thanks in Advance,

Uzair.

Best Answer chosen by Admin (Salesforce Developers) 
SFFSFF

You cannot modify the contents of system.trigger.new in an after trigger. If you try, you get this error message.

 

Good luck!

All Answers

jd123jd123

Hi

 

i think Counter__c is formula field

 

you can update the Formula field beacuse it is read only.

uzairuzair

Thanks for your quick reply.

 

The field 'Counter__c' is a number field.

jd123jd123

just see in the pagelayout is it Read only field checkbox is true??

 

just double click on the field.

uzairuzair

Thanks again.

 

I checked it and it is not a Read only field.

 

When I'm using the below code I'm able to increment the value.

 

trigger tgrCounter on Mileage__c (before insert, before update) {
    for(Mileage__c Mlg : Trigger.new){
        Mlg.Counter__c = Mlg.Counter__c+1;
    }
}

 But when I'm using for 'after insert' and 'after update' facing the problem.

jd123jd123
try this
trigger tgrCounter on Mileage__c (before insert, before update) { for(Mileage__c Mlg : Trigger.new){ Mlg.Counter__c = Mlg.Counter__c+1; } }
SFFSFF

You cannot modify the contents of system.trigger.new in an after trigger. If you try, you get this error message.

 

Good luck!

This was selected as the best answer
Alex.AcostaAlex.Acosta

SFF is correct, you'll need to requery all your records if you want to modify their values and insert them. Otherwise use a before trigger. Also make sure you don't get yourself caught in an endless loop!

uzairuzair

Thanks to All for your help.