Activity Forums Salesforce® Discussions Why we can't use DML before trigger in Salesforce?

  • Prachi

    Member
    July 17, 2018 at 9:32 am

    Hello Madhulika,
    In Before Triggers, actions are being performed before you commit the record to the database. This is where you usually do validations or updates to the same object. You can skip the DML operations here as whatever values you give in your code is automatically assigned to that record.

    • This reply was modified 6 years, 4 months ago by  Prachi.
  • shariq

    Member
    September 18, 2018 at 1:25 am

    Hi,

    We can use DML in before trigger but for different sobject, it depends upon your logic, if performed on same sobject then it will cause problem of recursion.

    Hope it helps.

  • Parul

    Member
    September 18, 2018 at 2:44 am

    The idea is to help avoid recursion. You cannot perform DML on the records which are stored in the trigger context variables. You can however retrieve them using the Ids (or create a new object referring to that record with the same Id ) and then update this. You still have to manage recursion properly though by using a static variable which can be resued over the contexts. For example:

     

    Trigger AccountTrigger on Account (after insert) {

    if(isAfter() && isInsert()){
    AccountTriggerHelper.performAfterInsert();
    }
    }

    public class AccountTriggerHelper {

    public static boolean isExecuting = false;

    public static void performAfterInsert(){

    if( TriggerHelper.isExecuting ){
    // if was executed during the same context
    // avoid recursion
    return;
    }

    TriggerHelper.isExecuting = true;

    //list of new instance of object to update.
    Account[] accounts = new Account[]{};

    for (Account a: Trigger.new) {
    //here the magic by creating a new instance using the same id
    Account aux = new Account(Id = a.Id);
    aux.Name = a.Id + 'Value forced to be set after by an extrange req';
    }
    //then update the new instance list.
    update accounts;

    }

    }

     

    Hope this will you.

     

    Thanks

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos