Doing before/after field comparisons in after_save logic hooks

bsoremsugar —  August 21, 2013 — 6 Comments

Often times in a logic hook, you may want to perform an action only if a value changes from one thing to another or only if it’s a newly added record. You can easily detect this in before_save logic hooks via the fetched_row attribute, but this isn’t possible in the after_save hook. But, if you string together both hooks, you can bring the fetched_row over from one to the other with ease. See the below code example for an idea on how to do this…

Here we simply store the fetched_row array into a static class member, which we can leverage in the subsequent hook later on in the file. Then in the after_save hook, we can easily tell if a record field has changed, or even if it’s a newly added record.

6 responses to Doing before/after field comparisons in after_save logic hooks

  1. 

    I always assumed that the logic hook class FieldChangeHook would be re-instantiated depending on the event driving it. I mean, I would expect $hook = new FieldChangeHook(); $hook->before_save_function($bean…) to happen, then $bean->save() in Sugarbean, and then $hook = new FieldChangeHook(); $hook->after_save_function($bean…)

    Is that not the case?

    I had to do something similar last week and ended up setting a $GLOBAL var in the before save and quickly unsetting in in the after save method. It felt hackish since I was using $GLOBAL but it works.

  2. 
    Stewart Osborne August 31, 2013 at 4:05 am

    Great technique!

  3. 

    I had 2 issues:

    1. self::$fetchedRow[$bean->id] += $bean->fetched_row; failed with no error, assume it was the operator
    so changed to: self::$fetchedRow = $bean->fetched_row; Then referenced like self::$fetchedRow[name]

    2. $this was blank so used $bean instead

    Not sure why you would want to store the whole row, but I guess it could be useful when comparing multiple fields.

  4. 

    This worked for me in Sugar 6.5:

    if ( $bean->fetched_row ) {
    self::$fetchedRow[$bean->id] = $bean->fetched_row;
    }

    And after:

    $id = $bean->id;
    // call on changed records only
    if ( isset(self::$fetchedRow[$id])…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s