1

I am new in developing apex.

Here is my trigger. When I try to update an account record, I get the error: "

Error:Apex trigger pfUpdate caused an unexpected exception, contact your administrator: pfUpdate: execution of BeforeUpdate caused by: System.FinalException: Record is read-only: ()"

I want the account to be updated only if the CR_Parent_Fax__c was false before and needs to be updated to TRUE. I do not want the trigger would get stuck in recursion. I also want to note that I have tried to change before trigger to after trigger, but did not do any better. Could someone help me to figure out what is wrong with my trigger? Any help would be appreciated.

trigger pfUpdate on Account (before update) {
    for (Account acc : Trigger.new) {
    // Access the "old" record by its ID in Trigger.oldMap
    Account oldacc = Trigger.oldMap.get(acc.Id);

    // Trigger.new records are conveniently the "new" versions!
    Boolean oldAccWpf = oldAcc.CR_Parent_Fax__c = true;
    Boolean newAccWOpf = acc.CR_Parent_Fax__c = true;

    // Check that the field was changed to the correct value
    if (!oldAccWpf && newAccWOpf) {
      acc.In_Active_Account__c  = true;
    }
  }
}

1 Answer 1

2

In Apex Code, = is assignment, while == is equality. What your code is doing here is assigning true to the field CR_Parent_Fax__c on the record obtained from Trigger.oldMap.get(acc.Id), which is not allowed (Trigger.old and Trigger.oldMap records are read-only). To fix this, use the equality operator:

Boolean oldAccWpf = oldAcc.CR_Parent_Fax__c == true;
Boolean newAccWOpf = acc.CR_Parent_Fax__c == true;

Or, as I commonly recommend, don't compare a Boolean to true, because it's already a Boolean:

if (!oldAcc.CR_Parent_Fax__c && acc.CR_Parent_Fax__c) {
1
  • Great, It works! That was so quick. Thanks a bunch :)
    – User Miro
    Commented May 23, 2018 at 23:33

You must log in to answer this question.

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