You need to sign in to do that
Don't have an account?
Trigger issue when trying to update related "Equipement's" last hours from object's hours field
Hello,
I am very new to APEX trigger writing and I am having this error.
My intention:
Basically when a user enters a new flight hours on the custom object Flight_Hours__c, and when the user also selects a checkbox called Update_Equipment_Last_Hours__c, that the trigger then references the related Equipment__c and updates that Equipments last hours.
My code:
trigger UpdateLastHours on Flight_Hours__c (after insert) {
for (Flight_Hours__c j : trigger.new)
{
If (j.Update_Equipment_Last_Hours__c = True)
{
j.Hours__c = j.Equipment__r.LastHours__c;
j.Hours_Date__c = j.Equipment__r.LastHoursDate__c;
}
}
}
My error:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UpdateLastHours caused an unexpected exception, contact your administrator: UpdateLastHours: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.UpdateLastHours: line 7, column 13
Any help would be greatful, and please excuse the noob if this is super simple :)
Thanks,
James
Try changing your trigger to 'before insert'
Yes, This trigger should be before insert.
Because for all after insert triggers we need to pass Id of the record at the time of creation of the object.
Thanks,
Kodisana
Thank you for the response!
So I changed it to before insert and I get a different error...
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger AverageMonthlyFlightHour caused an unexpected exception, contact your administrator: AverageMonthlyFlightHour: execution of AfterInsert caused by: System.ListException: List index out of bounds: 0: Trigger.AverageMonthlyFlightHour: line 57, column 31
This Trigger.AverageMonthlyFlightHour is another trigger on the flight hours__c but I didn't write this one. Below are the rows copied out of that trigger
list<Configuration_Parameters__c> configParam = new list<Configuration_Parameters__c>([Select Param_Value__c, Id, Param_Name__c From Configuration_Parameters__c where Param_Name__c =: 'MAX_ROWS_AVERAGE_MONTHLY_FLIGHT_HOURS']);
ParamValue = Integer.valueOf(configParam.get(0).Param_Value__c);
if(ParamValue == 1)
{
ParamValue = 2;
}
I think this is because your select statement is returning no records, so you are referring to a null list.
You should make a check that the list size is greater than zero.
list<Configuration_Parameters__c> configParam = new list<Configuration_Parameters__c>([Select Param_Value__c, Id, Param_Name__c From Configuration_Parameters__c where Param_Name__c =: 'MAX_ROWS_AVERAGE_MONTHLY_FLIGHT_HOURS']);
If(configParam.size() > 0)
{
ParamValue = Integer.valueOf(configParam.get(0).Param_Value__c);
if(ParamValue == 1)
{
ParamValue = 2;
}
}