+ Start a Discussion
Jacek DJacek D 

How to run an Apex trigger based on a change in a formula field?

I'm (still) totally green to Apex, so please be patient ;)

 

I have a trigger that updates the record that triggers it and creates a new record in the same object. It works nicely when using 'after update'. But what I actually need that trigger to do is run when a formula changes the value from false to true.

 

That formula is quite complex and using cross-object references and roll-ups to calculate the values, so there is not necessarily an action on the record happening to change the value.

 

My thought was to set it to 'after insert', hoping that the trigger will run every now and then to check whether the conditions are ok to run. But maybe I don't understand properly how this works.

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

If you don't need instant notification that the formula field has changed, you could use scheduled apex and schedule a class to run every hour, check and then trigger some activity.

 

There's docs at: 

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

All Answers

bob_buzzardbob_buzzard

Unfortunately you can't do this - formula fields are calculated on the fly when the record is retrieved from the database, so that field isn't affected when its components change.  One way I've handled this in the past is to change the formula field to a regular field and use a workflow field update to update the value based on the formula.  

Jacek DJacek D

That is indeed unfortunate. I was hoping I could schedule the trigger to check every now and then whether the conditions for firing are true or not.

 

The problem with my formula is that it is calculated automatically based (among other factors) on numbers that come from roll-ups. Meaning if a product meets a certain threshold in sales, I need the trigger to run. There is not really an action taking place - except for data import on the child object. Maybe you have an idea for a workflow in this case?

bob_buzzardbob_buzzard

If you don't need instant notification that the formula field has changed, you could use scheduled apex and schedule a class to run every hour, check and then trigger some activity.

 

There's docs at: 

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

This was selected as the best answer
Jacek DJacek D

Thanks for the pointer! I will look into it!

Viktor BakanovViktor Bakanov
Jacek D, Hi!
Did you resolve that? I have faced with the same thing....