Activity Forums Salesforce® Discussions How to update the Same Record in After Trigger context in Salesforce?

  • shariq

    Member
    September 22, 2018 at 6:35 pm

    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;
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos