Monday, January 27, 2014

Let’s say we have to update the same record in After Trigger context. Is there any way or workaround

Let’s say we have to update the same record in After Trigger context. Is there any way or workaround

If we create a new instance of an 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 not get a read only error. This is because in Apex, the SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations. The below snippet of code illustrated this working and not working.
List<Contact> originals = new List<Contact>();
if(mirrorResultMap.values().size() > 0)
{
                for(Contact origContact : contactRecs.values())
                {
                                Contact mirrorContact = mirrorResultMap.get(origContact.Id);
                                //origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original Record tot he Mirror Record WILL FAIL
                                Contact origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c = mirrorContact.Id); //This will WORK
                                originals.add(origContactUpdate);
                }
                //update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL RECORDS IN MEMORY
                update originals;
}
Credit goes to Cory Cowgill for this Blog Entry.


No comments:

Post a Comment