Activity Forums Salesforce® Discussions Why we cant insert/update fields in after triggers in that Salesforce Sobject?

  • Radhakrishna

    Member
    July 4, 2017 at 9:32 am

    Hello Shariq,

    You may be wondering why so many triggers are before triggers. There’s a good reason – they’re simpler to use. If you need to make any changes to a record entering your after trigger, you have to do a DML statement. This isn’t necessary in a before trigger – changes to records entering your trigger always save!

    The specific use case of an after trigger is when you need to associate any record to a record being created in your trigger. Here’s an example:

    // Automatically create an Opp when an Account is created
    trigger AutoOpp on Account(after insert) {
        List<Opportunity> newOpps = new List<Opportunity>();
        for (Account acc : Trigger.new) {
            Opportunity opp = new Opportunity();
            opp.Name = acc.Name + ‘ Opportunity’;
            opp.StageName = ‘Prospecting’;
            opp.CloseDate = Date.today() + 90;
            opp.AccountId = acc.Id; // Use the trigger record’s ID
            newOpps.add(opp);
        }
        insert newOpps;
    }
  • Parul

    Member
    September 30, 2018 at 8:34 pm

    Hello Shariq,

    Because in after trigger we may need DML operation for insert and update while in before we don’t need DML. generally. That’s why we can’t insert and update in after triggers in sobject.

    Thanks.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos