+ 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;
    if(EventsToUpdate.size() > 0){
        update EventsToUpdate;

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



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)){
    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)
            Events__c eventRec = new Events__c(id=event.Id);
            eventRec.Client_Services__c =oppMap.get(event.Opportunity__c).Engineer__c; 
    if(EventsToUpdate.size() > 0){
        update EventsToUpdate;