How to use client and server side code in UI actions without errors
The purpose of this article is to describe how the client and server-side scripts work in a client-side UI Action. The interaction between the two is not the most intuitive thing and can lead to errors on a form if it is not handled correctly. The problem generally is that you will be using client-side APIs and server-side APIs as well as possibly referencing client-side and server-side objects all in the same script.
If it is not correct, the UI action will cause errors. Some symptoms of that may be a blank page loading after clicking the UI action, right-click context menu on the form failing to display, and possibly other unexpected results.
The key to getting this right is using functions to wrap your client and server side code into separate closures. That way, if an API isn’t present at the time the script executes, it shouldn’t be a big deal as long as that function isn’t being called. When you click on a client-side UI action, the function specified in the Onclick field will be called.
This is where you should place any client side code. In your Onclick function, you have access to the g_form, g_user and any other client-side objects and APIs. You do not have access to server-side objects and APIs like current or gs methods here. In order to access server-side objects and APIs you need another function and that needs to be called whenever the window object is not defined.
Then, in your server-side function you’ll have access to server-side objects and APIs like current, and the gs methods but will not have access to client-side APIs like g_form.
When clicking the UI action the processing will look something like this:
- Onclick function is called, which in this example is doSubmit.
- Window is defined so nothing else should happen.
- Once to the server, the UI action code executes a second time but this time, doSubmit is never called.
- Window is not defined here so doServerStuff is called
- doServerStuff runs and does as intended.
By using functions, you can control when certain parts of your code execute and avoid errors caused by an API or object being undefined.