Normally when you try to update a
record in After Trigger Context you will get "Record is read only"
Error.
Following is the workaround to prevent this
If we create a new instance of a SObject in the Apex Trigger in memory using the Id of the newly created record as provided in the After Trigger context, we can perform an Update DML statement and will not get a read only error. This is because in Apex, SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations
List<Contact>
newcontactlist = new List<Contact>();
if(triggerResultsMap.values().size() > 0){
for(Contact
actualContact : contactRecs.values()){
Contact
dupecontact = triggerResultsMap.get(actualContact.Id);
//actualContact.Linked_Contact__c
= dupecontact.Id; //This will Fail
Contact
origContactUpdate = new Contact(Id=actualContact.Id, Linked_Contact__c =
dupecontact.Id); //This will WORK
newcontactlist.add(origContactUpdate);
}
//update
contactRecs.values(); //Update the Records -- this wil fail as we are updating
main recods
update
newcontactlist;
}
No comments:
Post a Comment