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
Liz MalmanLiz Malman 

Apex Trigger set to Update current record

I have an Event object and an Opportunity object. On an Event record, there is a field to lookup an opportunity that it is related to, called Opportunity, and there is a lookup field called Client Services. I'm trying to write a trigger that when the Opportunity field is filled out and the Client Services field is blank, the event will update with the related opportunity's Client Services field. 

Here is my code:
trigger EventClientServiceTrigger on Events__c (after update, after insert) {
    list<Events__c> EventsToUpdate = new list<Events__c>();
    
    for (Events__c e:Trigger.new){
        if (e.Client_Services__c == null && e.Opportunity__c != null && !checkRecursive.SetOfIDs.contains(e.Id)){
                Opportunity opp = new Opportunity();
                opp.Id = e.Opportunity__c;
                e.Client_Services__c = opp.Engineer__c;
                EventsToUpdate.add(e);
        }
    }    
    if(EventsToUpdate.size() > 0){
        update EventsToUpdate;
    }    

I get an error saying the "Record is read-only". Does anyone know why this might be?

Thanks,

Liz

Maharajan CMaharajan C
Hi Liz,

Please try the below trigger:

In After Context trigger.New is Read Only so you can't make update on this. For this you need to query the Record again from database.

trigger EventClientServiceTrigger on Events__c (after insert, after update) {
    list<Events__c> EventsToUpdate = new list<Events__c>();
    List<Events__c> evnList = new List<Events__c>();
    set<Id> oppIds = new set<Id>();
    set<Id> eventIds = new set<Id>();
    Map<Id,Opportunity> oppMap;
    for (Events__c e:Trigger.new){
        if (e.Client_Services__c == null && e.Opportunity__c != null && !checkRecursive.SetOfIDs.contains(e.Id)){
                oppIds.add(e.Opportunity__c);
                eventIds.add(e.Id);
          }
    } 
    
    if(oppIds.size() > 0)
    {
        oppMap = new Map<Id,Opportunity>([select Id,Engineer__c from Opportunity where Id IN: oppIds]);
    }
    
    evnList = [Select Id, Client_Services__c from Events__c where Id IN: eventIds];
    
    for(Events__c event : evnList)
    {
        if(oppMap.containsKey(event.Opportunity__c))
        {
            Events__c eventRec = new Events__c(id=event.Id);
            eventRec.Client_Services__c =oppMap.get(event.Opportunity__c).Engineer__c; 
            EventsToUpdate.add(eventRec);
        }
    }
    
    if(EventsToUpdate.size() > 0){
        update EventsToUpdate;
    }   
    
}

Thanks,
Maharajan.C