I am not a developer and I do not yet write Apex code very well. I need an Apex Trigger to do the following:
- If field "A" is null, update this field with the value from another field "B"
- Field "A" is a lookup field tied to object "oA"
- Field "B" is a formula field that gets its value from another object "ObjC"
- Object "ObjA" and Object "ObjC" are not related
- Fields "A" and "B" both reside in the Lead object
- 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?