+ Start a Discussion
Linda 98Linda 98 

Change checkbox after trigger invoked.

Hi

I am having an after update trigger which fires when a checkbox is set to true. It then creates records in the related object.
After creating(after trigger functionality is implemented), I want to make the checkbox again as false programmatically. How can I achieve this?
I tried to make it false after building the list, but I am facing Read only error.

Thanks
Deepali KulshresthaDeepali Kulshrestha
Hi Linda,

In this condition you can use only 'before update'  trigger because the field value of the object can be changed using trigger.new but only in case of before triggers. But in case of after triggers changing the values of the records in trigger.new context will throw an exception as "Record is read only".
Note:
1. Trigger.new and trigger.old are read only.
2. An object can change its own field values only in before trigger: trigger.new.
3. In all cases other than mentioned in point 2; fields values cannot be changed in trigger.new and would cause run time exception "record is read only".

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.
Linda 98Linda 98
Yes. I agree. But when I go with before update, I am encountering this error.
SELF_REFERENCE_FROM_TRIGGER, Object is currently in trigger, therefore, it cannot recursively update itself:
So how should I achieve this ?
Deepali KulshresthaDeepali Kulshrestha
Hi Linda,

This error occurs when you make DML operation in 'before Update'.Any changes made in a before-insert/before-update trigger will automatically be applied without a DML operation.
Try the following example it may be helpful for you:
Trigger:
trigger OpportunityTrigger on Opportunity (before Update){
        if(trigger.isUpdate&& trigger.isBefore){
        OpportunityTriggerHandler.OpportunityTriggerMethod(trigger.new);
        }
}
Trigger-Handler:
public class OpportunityTriggerHandler {
    public static void OpportunityTriggerMethod(List<Opportunity> oppList){
    for(Opportunity opp : oppList){
         opp.StageName = 'Prospecting';
         opp.CloseDate = Date.Today()+15;
    }
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha