1

I am not a developer and I do not yet write Apex code very well. I need an Apex Trigger to do the following:

  1. If field "A" is null, update this field with the value from another field "B"
  2. Field "A" is a lookup field tied to object "oA"
  3. Field "B" is a formula field that gets its value from another object "ObjC"
  4. Object "ObjA" and Object "ObjC" are not related
  5. Fields "A" and "B" both reside in the Lead object
  6. Objects "ObjA" and "ObjC" are related to the Lead object via lookup relationships

Following is my attempt to write a Lead Trigger:

trigger ForceFieldAName on Lead (after insert, after update ) {

  Set<String> sSources = new Set<String>();
  for(Lead l : Trigger.new) {        
    if(l.Field_B__c != null) sSources.add(l.Field_B__c);
  }

  Map<String, ObjC__c> mObjCs = new Map<String, ObjC__c>();  
  for(ObjC_c crInstance : [SELECT Id, Name FROM ObjC__c WHERE Name IN :sSources]) {
    mObjCs.put(crInstance.Name, crInstance);
  }

    for(Lead l : Trigger.new) {        
        if(l.Field_B__c != null) {
            if(mObjC_s.containsKey(l.Field_B__c)) {        
        l.Field_A__c = mObjCs.get(l.Field_B__c).Id;        
      }
        }
    }  
}

I get an error from the last row "l.Field_A__c = mObjCs.get(l.Field_B__c).Id;" that says the "Record is Read Only". Does this mean I cannot use the value from the formula field to update the value in a lookup field in the Apex Trigger?

1
  • You can use the value of the formula field but you can't do it by updating Trigger.new in an after trigger - you'll need to use explicit DML in the after trigger; Trigger.new can be updated in before triggers so depending on your use case - you should see if this can be done in a before trigger
    – cropredy
    Commented Jul 24, 2015 at 0:24

1 Answer 1

1

The error is due to assigning a value to a field in the Trigger.new list, take a look here for trigger context.
enter image description here

You must log in to answer this question.

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