Zope And MySQL - Adding Things Up (
Page 6 of 9 )
Next, how about adding a new record to
the table?
Here too, the process is similar - first create a Z SQL Method containing an
INSERT query, and then invoke the Method from a DTML script. There's one important
difference here, though - since the data to be entered is not hard-wired, but
rather user-defined, the query string must be constructed dynamically.
In order to see how this works, create a new Z SQL Method - I've called mine
"insertMethod" - and add the following values to the argument field:
title director cast genre
These arguments can then be used to dynamically construct a query. Here's what
I would put into the query template:
INSERT INTO dvd (title, director, cast, genre) values (<dtml-sqlvar
title
type="string">, <dtml-sqlvar director type="string">,
<dtml-sqlvar cast
type="string">, <dtml-sqlvar genre type="string">)
I'm sure the linkage between the arguments and the query template is now clear
- the arguments passed to the Z SQL Method can be accessed in the query template
to dynamically create a new INSERT query every time the method is invoked.
In case you're wondering, the <dtml-sqlvar> construct is very similar to the
<dtml-var> construct, except that it comes with a couple of additional, SQL-specific
features - for example, the "type" attribute, which makes it possible to specify
the data type of the values being inserted and thereby catch errors before the
data gets inserted into the database, and the ability to automatically "quote"
values before inserting them into the database.
So that takes care of the SQL. Now, how about a form to invoke this method and
pass arguments to it?
<dtml-var standard_html_header>
<h2>Add DVD</h2>
<form action="someFormProcessor"
method="POST">
<table border=0>
<tr>
<td>Title</td>
<td><input
name="title" width=30 value=""></td>
</tr>
<tr>
<td>Director</td>
<td><input
name="director" width=30 value=""></td>
</tr>
<tr>
<td>Cast</td>
<td><input
name="cast" width=30 value=""></td>
</tr>
<tr>
<td>Genre</td>
<td><input
name="genre" width=30 value=""></td>
</tr>
<tr>
<td colspan=2 align=center>
<input
type="submit" name="submit" value="Add DVD">
</td>
</tr>
</table>
</form>
<dtml-var
standard_html_footer>
Here's what it looks like:
When this form is submitted, the form processor will need to invoke the "insertMethod"
Z SQL Method, use the form variables to dynamically fill up the query template
and execute the INSERT query. Here's what it looks like:
<dtml-var standard_html_header>
<dtml-call insertMethod>
<h2>Item
added!</h2>
<p>
<a href="list">View the entire collection</a> or
<a href="add">add
another title</a>
<dtml-var standard_html_footer>
Fairly simple, this - the <dtml-call> construct is used to invoke the selected
Z SQL Method, and a neat little result screen is displayed. The form variables
submitted to the form processor are automatically picked up by the Z SQL Method
and used to construct the INSERT query string.
Here's what it looks like: