Download a File in a Logic Hook

Today on IRC a fine fellow posted an interesting challenge. How do you prompt a file download while in a logic hook? To make it more interesting he offered scotch as a reward.

I was hooked.

Why return a file in a logic hook? There are many possibilities. Perhaps a quote or invoice gets updated and you want to generate a new PDF of the quote/invoice on any change. Or perhaps whenever an account gets added you need a packing slip created.

To illustrate how this could be done here is a simple example that downloads a text file whenever a contact gets added or updated to have a title of CEO. First is the before_save logic hook that captures when a value gets changed. In the require_download function below we check to see if the title value has changed. If so, set a session variable to be used to both tell the next (after_ui_frame) hook to execute and to pass data that could be used when generating the file.

Next we have an after_ui_frame hook that checks to see if the request is a non-AJAX request, if the current action is the Detail View, and if our session variable is set. If so, then output some javascript to redirect the browser to our custom download file action. In this URL we could pass the bean ID if needed. Notice the to_pdf. If you don’t add this you will get some unwanted content added to your generated file.

Here is the CEO_Download.php file that spits out a text file for the user to save. Notice that the name of the file matches the action param in the redirect URL above. If that isn’t the case in your situation you will want to create a custom entry point instead or add the action to the module’s controller. Yeah, there’s always another way to do something when working with SugarCRM.

Below is what the logic_hooks.php definition looks like:

Note: Ideally, the before_save should be an after_save logic hook to ensure that the save actually happened. Do it that way first, but be aware that you may have issues with the fetched_row having updated values instead of the original values depending on which version of SugarCRM you are on. See the comments on this dev blog post for more information: SugarCRM Developers Blog: Create new project on Opportunity stage change via a logic hook.

Moral of the story? I’ll do anything for a good scotch.


I make high quality solutions at an alarming rate.
No comments yet.

Leave a Reply