Activity Forums Salesforce® Discussions What will happen if you try to update record in After Trigger Context in Salesforce?

  • What will happen if you try to update record in After Trigger Context in Salesforce?

  • Aman

    Member
    September 22, 2018 at 6:34 pm

    What will happen if you try to update record in After Trigger Context in Salesforce?

  • shariq

    Member
    September 24, 2018 at 4:49 am

    Typically, if you are populating trigger record fields, it is best to use a before trigger, because it does not add transaction cost. However, if you absolutely must populate information to trigger records in an after context, you can re-query for them and act on this new reference, then perform an update. This strategy increases the cost in both DML Statements and SOQL.

  • Avnish Yadav

    Member
    September 24, 2018 at 1:14 pm

    Hello,
    Actually, you can perform DML in trigger from future methods with callout=true. You can call this method in the trigger, but they will be executed after trigger ends, so no error will happen. For example, I used it to automatically fill some fields that require ID of record, that can't be received in Before trigger.
    Thanks.

  • Parul

    Member
    September 28, 2018 at 8:40 pm

    you can perform DML in trigger from future methods with callout=true.you can re-query for them and act on this new reference, then perform an update.

  • ozerm fried

    Member
    December 27, 2021 at 4:20 pm

    If you have the Id of the record you can just instantiate a new instance of the record without querying for it, saving a SOQL call.
    Like so:Account a = new Account(Id = accountId);

  • Emilyn

    Member
    January 13, 2022 at 9:55 pm

    If you did this, it would fail because you're essentially trying to make a duplicate record here. You are correct, however, in that the After context has access to the ID(s) of the updated record(s). In fact, with After Update we have use of trigger.new, which contains not only the ID(s) but all the fields for the updated records. To make changes to any of these fields, you could simply loop through trigger.new, updating the field values if they need to be updated. This is important and is one of the many reasons why it's not best practice to perform updates to updated records in After Update - if you don't validate those field values and instead set up the loop to always change them and update all the records again, you will end up in a potentially infinite loop.
    Long story short, don't do this. Use Before Update unless it's absolutely necessary.

Viewing 1 - 6 of 6 posts

Log In to reply.

Popular Salesforce Blogs