In this article we will discuss how to minimize the amount of code that handles Javascript on Add/Edit pages. Making your code data-driven will help you easily manage forms with a huge numbers of fields. We will be taking care of functionality like showing/hiding fields, making fields readonly, required, disabled etc.
This approach will involve the following steps
1. Creating and populating database tables to store triggers ( when to apply the logic ) and actions ( what happens when trigger goes off )
2. Server-side PHP and C# code that passes this data to Javascript
3. Javascript code itself that listens to “change” event and implements the logic defined in the database.
Database tables
Triggers table. The structure is fairly simple. You can see that we store table name, page type, field name and what event we are listening to. In this article we will only show how to implement the most common “change” event as it covers 95% of required functionality.
Actions table is a details one while triggers is a master. They are linked by trigger_id field. This table knows what condition to check and what action to perform. Lets take a look at the first row and try to decipher it.
The action is tied to trigger #1 ( change event of Country field on the Edit page of customers table). The condition is equal and the condition_value is ‘USA’. Which means that when Country field equals ‘USA’ we should proceed with our action. And the action itself is showing of the Region field.
And here is the SQL script that will create both tables for you with sample data.
Server-side code
Server-side code goes to BeforeDisplay event of each page where this functionality needs to be implemented. In our situation this code goes to BeforeDisplay event of Customers table Edit page. The code itself is fairly straightforward. It just dumps all the data from actions and triggers tables and makes this data available in Javascript via proxy object.
Note that for better code structure you need to create an external PHP or C# file, define a function there and place this code into that function. Then in all BeforeDisplay events
PHP code
C# code
Javascript code
Javascript code goes to Javascript OnLoad event of the page where the action should happen, in our case this is Javascript OnLoad event of Customers table Edit page. The same idea with creating a Javascript function and calling from the external file is also valid here.
You can extend this code by adding more conditions types and more actions. Check inline comments for more info.
Enjoy!