working on this trigger for 2 custom objects in a master detail relationship. the insert
part works perfectly, just am struggling with the update
portion. i've included the entire code in case my previous map needs to be used. basically, i'm trying to change the type custom field to null if when UPDATING the end date field is set to a value (no longer null).
trigger RoleHistoryAfterTrigger on Role_History__c (after update, after insert) {
Map<Id, Rep__c> parentReps = new Map<Id, Rep__c>();
List<Id> listIds = new List<Id>();
if(Trigger.isInsert) {
for(Role_History__c roles :Trigger.New) {
listIds.add(roles.Rep__c);
}
parentReps = new Map<Id, Rep__c>([SELECT Id, Rep_Type__c, (SELECT Id, Type__c FROM Role_Histories__r WHERE End_Date__c = null ORDER BY CreatedDate DESC LIMIT 1) FROM Rep__c WHERE Id IN :listIds]);
for(Rep__c reps :parentReps.values()) {
for(Role_History__c roles :reps.Role_Histories__r) {
reps.Rep_Type__c = roles.Type__c;
}
}
update parentReps.values();
}
if(Trigger.isUpdate) {
for(Role_History__c roles :Trigger.New) {
if(roles.End_Date__c != null) {
roles.Type__c = null;
}
}
}
}
i though this would work but i'm getting this error-
RoleHistoryAfterTrigger: execution of AfterUpdate caused by: System.FinalException: Record is read-only Trigger.RoleHistoryAfterTrigger: line 29, column 1
the record is definitely not read-only because when i comment out the if(Trigger.isUpdate)
code i no longer get the error. what am i missing to get this to function properly?