0

I am creating record in energy object and have to update a field with user entered value + static value while creating and updating .

trigger testews on Energy__c (after insert,after update) {

    if(trigger.isafter && trigger.isupdate){
      energyHandler.onAfterupdate(trigger.new,trigger.oldmap);
    }
    if(trigger.isafter && trigger.isinsert){
        energyHandler.onAfterInsert(trigger.new);
    }

}

apex class

public class energyHandler {
    public static boolean isExecuting = false;
    public static void onAfterupdate(List<Energy__c> lstlask,Map<id,Energy__c> energyold) {

      if(energyHandler.isExecuting ){
            // if was executed during the same context 
            // avoid recursion
            return;
      }

      energyHandler.isExecuting = true; 
      List<Energy__c> Updtaeenergy=new List<Energy__c>();
      for(Energy__c energy: lstlask) {
        if(energyold.get(energy.id).energytitle__c!=energy.energytitle__c) {
            if(energy.energytitle__c==null){
                energy.energytitle__c= 'Success';
            } else {
                energy.energytitle__c='Success'+energy.energytitle__c;
            }
        }
        Updtaeenergy.add(energy);     
      }

      if(Updtaeenergy.size()>0){
        update Updtaeenergy;  
      }

    }

    public static void onAfterInsert(List<Energy__c> lstlask) {
        List<Energy__c> newenergy=new List<Energy__c>();
        for(Energy__c energy: lstlask) {
            if(energy.energytitle__c==null){
                energy.energytitle__c= 'Success';
            } else {
                energy.energytitle__c='Success'+energy.energytitle__c;
            }
            newenergy.add(energy); 
        }
        if(newenergy.size()>0){
            update newenergy;  
        }
    }


}

I am getting error like execution of

AfterInsert caused by: System.FinalException: Record is read-only:

Please help me out .

1 Answer 1

2

you can't change context records in trigger on after events. Read Triggers Apex Developer Guide

  • After triggers are used to access field values that are set by the system (such as a record's Id or LastModifiedDate field), and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue. The records that fire the after trigger are read-only.

if you want to do changes in trigger context records you have to do it in before events

In order to have these changes to trigger context records to be saved, you don't need to perform DML in before event on these records.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .