function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sean.gorman@ipc.comsean.gorman@ipc.com 

Trigger Advice: Using trigger. old/new to check when to create new related object

Hi,

 

I am writing a trigger to create a new object related to an opportunity when a certain thing happens.

 

Right now that 'certain thing' is a button click that sets a checkbox. That button checks to see if a review has already been created by checking to see if the checkbox is set and if not sets it. When an update happens where the RevRequired__c checkbox = 1 then I am going to insert a new related review.

 

Now then. What would the best practice be?

Use the trigger old/new map to see if the checkbox was checked before and is now.

Use 2 fields, (RevRequired__c and RevDone__c) one to check if it has been done and one to kick off the process.

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You can use a "rising edge" trigger, certainly (to borrow terminology from the field of electronic engineering).

 

for(Obj record:Trigger.new) {
  if(record.revrequired__c&&!trigger.oldmap.get(record.id).revrequired__c) {
    // process rising edge change
  }
}

 

All Answers

sfdcfoxsfdcfox

You can use a "rising edge" trigger, certainly (to borrow terminology from the field of electronic engineering).

 

for(Obj record:Trigger.new) {
  if(record.revrequired__c&&!trigger.oldmap.get(record.id).revrequired__c) {
    // process rising edge change
  }
}

 

This was selected as the best answer
sean.gorman@ipc.comsean.gorman@ipc.com

Thank you (again)  Fox.

 

So this means that I will be running a BEFORE UPDATE trigger and writing a new object in that trigger?

 

Reiterating as I want to make sure that I can insert the new Review in the middle of the update for the Opportunity...(this might seem like a stupid question but I recall having a problem here)

sfdcfoxsfdcfox

You can use an after DML event for this purpose. Before DML events are events that occur before an initial database commit. This is the perfect time to modify incoming data and validate user input. After DML events are the time to update related records, send emails, and do other sorts of things that you'd do only on data that was "guaranteed" to be saved to the database. While you can indeed technically validate in an after DML event, it is generally not the appropriate place to do so (with the exception of after undelete DML events, because there is no "before undelete" event). Trigger.old and Trigger.new contain the same data in "before" and "after" DML events (not the same as each other, but the same information across the before/after event horizon).

sean.gorman@ipc.comsean.gorman@ipc.com
thanks sfdcfox