Activity › Forums › Salesforce® Discussions › Why we cant insert/update fields in after triggers in that Salesforce Sobject?
Tagged: After Trigger, DML Operation, DML Statement, Field Update, Salesforce sObject, Salesforce Triggers, Trigger New
-
Why we cant insert/update fields in after triggers in that Salesforce Sobject?
Posted by shariq on July 4, 2017 at 5:24 AMIn Salesforce, why we cannot insert/update fields in after triggers in that Sobject?
Parul replied 7 years, 7 months ago 3 Members · 2 Replies -
2 Replies
-
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; } - [adinserter block='9']
-
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.