On occasion I run into a logic hook use case that ultimately exposes a limitation of the framework, or generates peculiar challenges during its implementation. Lets review some of these items in hopes they may help you avoid frustration and save you some time.
before_save vs. after_save
It is not uncommon to stumble upon references to either of these terms as one reads about logic hooks. They refer to the timing of the execution of your logic hook code. A before_save hook triggers your code before the record a SugarCRM user is interacting with is physically written to the database, and an after_save hook triggers it after the data has been written to the database.
While those conditions are easy to understand, the same cannot be said for the technical subtleties each carry. It is important to understand these subtleties because some may require one to change from using before_save instead of after_save or vice-versa. More importantly, being aware of these subtleties helps us reduce the amount of time that would otherwise be wasted on troubleshooting the problems the subtleties bring about.
When it comes to a before_save trigger, timing is indeed everything. And this is the thing you most need to be concerned about. Here are a couple of related examples of some behaviors you should expect to see:
- Related records created via the hook may not immediately appear on the corresponding subpanel.
- The value in the case_number field from the Cases module will not be available.
- Using $object->retrieve() to access the record in question will fail.
Coincidentally, using an after_save hook in place of a before_save hook should resolve all of the above issues. However, there is a very important point about the after_save hook which one must remember: one cannot access custom fields by default.
Normally, one can access fields from a record by means of the $bean object. That allows one to read or change the values of the record that triggered the logic hook. To do this, one would use code similar to the following: $bean->field_name or $bean->my_custom_field_c.
For scenarios where an after_save hook is being used, the custom fields must be reloaded. Without reloading them, a line of code such as $bean->my_custom_field_c would not work, either for read or write purposes. So how do we reload the custom fields? It is rather simple.
To solve this problem, simply add the following code prior to any code intended to access a custom field:
Are there some other gotchas that you have encountered? If so, please share them and how you solved them.