+ Start a Discussion
Reshmi Sangani 5Reshmi Sangani 5 

I am trying to write a trigger to update a field on Account record .

There is a field on the Account record called "Ultimate Parent ID" .(which is a formula field to calculate the Parent Account ID for that Account).
This field is a 15 character text formula field.
I am trying to write an after trigger to update a field "ultimate Parent ID 18".
The functionality of this trigger is to convert the above 15 digit ID to an 18 digit salesforce ID and store it in a field on the Account record.
Apex:
public without sharing class AccTriggerHandlerUpdUltParentId extends TriggerHandlerBase {

    public virtual override void mainEntry(TriggerParameters tp) {

        UpdUltParentID(tp);
    }

    public virtual override void inProgressEntry(TriggerParameters tp) {

        UpdUltParentID(tp);
    }


    void UpdUltParentID(TriggerParameters tp) {

        List < Account > lstToUpdate = new List < Account > ();
        List < Account > ListAcc = (List < Account > ) tp.newList;
        Map < Id, Account > newMapAcc = (Map < Id, Account > ) tp.newMap;
        Map < Id, Account > oldMapAcc = (Map < Id, Account > ) tp.oldMap;
        Set < Id > setAccountIds = new Set < Id > ();
        string idStr;
        id idval;
         for(Account acc : ListAcc){
            setAccountIds.add(acc.Id);
         }

        if (tp.tEvent == 'afterUpdate') {
            for (Account acctNew: ListAcc) {
                    acctNew.Ultimate_Parent_ID_18__c = acctNew.Ultimate_Parent_Id__c;
                    idval = acctNew.Ultimate_Parent_ID_18__c;
                    acctNew.Ultimate_Parent_ID_18__c = idval;
                    lstToUpdate.add(acctNew);
               // }

            }
        }

    }
}
 I am receiving the following error:

Question: Should this trigger be in an Afterupdate or before Update?
I tried in the context of After but there was an error saying "record is read only".
Thank you for the help!
 
Reshmi Sangani 5Reshmi Sangani 5
While executing the trigger in afterupdate context the following error is showing up:
Error:Apex trigger AccountTrigger caused an unexpected exception, contact your administrator: AccountTrigger: execution of AfterUpdate caused by: System.FinalException: Record is read-only: ()
Saravana Bharathi 1Saravana Bharathi 1
Hi Reshmi,

Trigger.new in After update, it will be read-only. instead try to change from after update to before update trigger event.

since, you want to update field value, try to change field value in before update event, 

Please refer salesforce trigger order of execution documentation.

If it solves, mark it as resolved and let us know.

Thanks