3

I have two custom objects:

Contract__c and Address__c.

Address__c has a value__c currency field on it.

Contract__c has a rollup summary field, which holds the maximum value of the attached addresses. The field name is: max_value__c. Contract__c also has another field called est_loss__c and a field called 'limit__c`.

So, I need to do the following:

I need to update the limit__c field on Contract__c based on the rollup field and the other currency field. I do this in my trigger as follows:

trigger ContractTrigger on Contract__c (after update) {

    for (Contract__c con : Trigger.new){

            if(con.est_limit__c < con.max_value__c){
                con.limit__c = con.est_limit__c;
            }
            if(con.est_limit__c >= con.max_value__c){
                con.limit__c = con.max_value__c;
            }
        }
        update(con);

}

All this looks pretty simple, but when I try this, it all fails. So, I can create a contract, and then I want to add an address. When I try to save the address, I get the following error:

 Review all error messages below to correct your data.
Apex trigger ContractTrigger caused an unexpected exception, contact your administrator: ContractTrigger: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.ContractTrigger

Can anyone see what I am doing wrong? As far as I know I don't have read-only fields... Tia.

1 Answer 1

2

You are doing an after update trigger and trying to update the records send to you via Trigger.new. Please see this page to see what actions are available in each type of trigger: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables.htm

In general, when you are attempting to update the record you are writing the trigger on you use before and when you want to create or edit a different record you use after.

Changing your trigger to a before update trigger should work find barring any other errors.

3
  • 1
    And, of course, removing the dml update statement.
    – sfdcfox
    Jan 9, 2015 at 21:29
  • Hello, no, the trigger does not work when I use a before update unfortunately. I then get the following error message: Apex trigger ContractTrigger caused an unexpected exception, contact your administrator: ContractTrigger: execution of BeforeUpdate caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.ContractTrigger: Here it is referring to the line with the update(con); statement.
    – Lily
    Jan 9, 2015 at 22:53
  • @Lily sfdcfox is correct. you must remove the DML statement. A before trigger doesn't require an update statement. Jan 13, 2015 at 15:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .