+ Start a Discussion
emandra_kfemandra_kf 

Apex Trigger and Workflow Rule Order of Execution Problem

I'm encountering a problem with an Apex trigger and a workflow rule on a custom object that I think relates to order of execution. Here's the scenario:

 

1.) Custom object has a Due Date field that is populated by an Apex trigger using a "before" trigger type.

 

2.) Workflow rule sends an Email Alert upon "only when record is created".

 

3.) The Email Alert uses an Email Template that includes Due Date, yet the Due Date is null (missing) in the email that is generated.

 

The Email Template is also used to send emails on an ad hoc basis, and in those cases the Due Date is displayed in the email as expected. Because of this, I do not believe there is a problem with the Email Tempalte or the Apex trigger.

 

Nonetheless, the standard order of execution would indicate the "before" trigger should fire prior to the workflow rule and the Due Date should be available to include in the email generated by the workflow rule.

 

Am I overlooking something? Any suggestions would be appreciated.

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

It works in my test org. Try checking the value in the debug logs. Maybe you have some sort of recursion that's causing it to read the wrong value?

All Answers

sfdcfoxsfdcfox

In light of the fact that the value would have been committed to the database even before the email is generated, it sounds like you may have some sort of bug on your hands. Try contacting technical support. I'll research this independently and see if I can replicate it.

sfdcfoxsfdcfox

It works in my test org. Try checking the value in the debug logs. Maybe you have some sort of recursion that's causing it to read the wrong value?

This was selected as the best answer
emandra_kfemandra_kf

Thank you for checking into it. I'll take a look at the debug logs as you suggest. Stay tuned.

emandra_kfemandra_kf

The debug logs proved to be helpful, and in the end, led me to the bug in my trigger. From what I could see in the logs, (1) the Before Insert trigger was not firing, (2) the workflow rules would run (sending the email without the Due Date, and then (3) the Before Update trigger would fire and calculate the Due Date.

 

I had a bug in my trigger that did not allow the trigger to run unless objectname.CreatedDate != NULL; thus, it would only fire as a Before Update. Once I fixed the bug and it fired as a Before Insert, the problem was solved.

 

Thank you for taking the time to help. I really appreciate it.