Reading a Row, Filling in the Fields
The SQL
Now, use the ZMI to create, inside your form folder, a Z SQL Method named testReadRow. Set up the following parameters:
- Connection ID
- Choose your test database adapter.
- Arguments
- Just "uid"
select * from simple_db where
<dtml-sqltest uid type="int">
The <dtml-sqltest ...> operator is a safe way to use user input for an SQL "where" test. The default test is "=".
The Script
Let's wrap this method in a simple Python script that will selectively use it. Create a Python Script with the id formSetup and the Python:
request = container.REQUEST
form = request.form
if form.has_key('uid') and not form.has_key('form.submitted') :
res = context.testReadRow().dictionaries()
if len(res) == 1:
row = res[0]
for key in row.keys():
form[key] = row[key]
Let's deconstruct this code.
The if test:
if form.has_key('uid') and not form.has_key('form.submitted')will make sure that this code does nothing if the form has already been submitted (we don't want to overwrite values the user just input). It also won't do anything if we don't have a "uid" variable in the form dictionary. (form.submitted is a hidden input that's part of every PFG form.)
If we have a uid variable and we won't be overwriting user input, then we call our SQL read method:
res = context.testReadRow().dictionaries()This will return the results of our SQL query in the form of a list of dictionaries. The dictionary entries will be in the form columnid:value.
Note that the uid value is being passed via the request variable, and doesn't need to be specified.
The rest of the code checks to make sure that we got one result, and throws all of its key:value pairs into the form dictionary -- just where our form will expect them.
The Form
Now, just go to the [override] pane of your form folder, and specify "here/formSetup" for your Form Setup Script.
Calling The Form
Hopefully, you've got a few rows in your table. Now, try calling your form with the URL:
http://localhost/testfolder/myform?uid=1Everything up to the question mark (the query string marker) should be the URL of your form folder. The "?uid=1" specifies that we want to use the data from the row where the uid is "1".
How would you actually get your users to such a URL? Typically, you'd have some sort of drill-down search that offered them a list of links constructed in this fashion.
Creating a drill-down template is left as an exercise for the reader.
