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
Saoni PaitandiSaoni Paitandi 

Trigger to count the number of record updation in a record of Account

Please help me in this: I have created a counter field in account and have written the code like this
trigger AccountUpdationCounter on Account (after update) {

for(Account acts:trigger.new){
if(Trigger.isUpdate){
acts.Counter__c=0;
acts.Counter__c=acts.Counter__c+1;
}
update acts;
}
}
Getting below error after updating from UI:Error:Apex trigger AccountUpdationCounter caused an unexpected exception, contact your administrator: AccountUpdationCounter: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.AccountUpdationCounter: line 4, column 1
Best Answer chosen by Saoni Paitandi
Waqar Hussain SFWaqar Hussain SF
Use before trigger as below
trigger AccountTrigger on Account (before update){
	
	if(Trigger.isUpdate){
		for(Account acts:trigger.new){
			if(acts.Counter__c == null)
			acts.Counter__c=1;
			else
			acts.Counter__c=acts.Counter__c+1;
		}
	}
}

 

All Answers

Waqar Hussain SFWaqar Hussain SF
Use before trigger as below
trigger AccountTrigger on Account (before update){
	
	if(Trigger.isUpdate){
		for(Account acts:trigger.new){
			if(acts.Counter__c == null)
			acts.Counter__c=1;
			else
			acts.Counter__c=acts.Counter__c+1;
		}
	}
}

 
This was selected as the best answer
Saoni PaitandiSaoni Paitandi
Hi Waqar,
Could you please explain me why you have taken before update?

Thanks,
Silpi
Waqar Hussain SFWaqar Hussain SF
Hi Silpi,

You can not perform dml operations in an after insert/after update trigger on same object on which trigger is developed.

Because in an after insert/update trigger, the records are read only in that context as they have been written, but not committed, to the database.

You can update/assign values in the trigger context in before trigger.

Regards,
Waqar
Saoni PaitandiSaoni Paitandi
Once Again thanks a lot Waqar!!!!
Adinarayana KesaniAdinarayana Kesani
Can you please provide the test class for this trigger?
Waqar Hussain SFWaqar Hussain SF
public class AccountTrigger_Test {
    public static testmethod void UnitTest() {
        Account acc = new Account();
        acc.Name = 'Test account';
        insert acc;

        acc.Name = 'Test Account2';
        update acc;

        acc.Name = 'Test Account 3';
        update acc;

    }
}
Adinarayana KesaniAdinarayana Kesani
Thank you Waqar :)