Create a form for related tables

by Paul Eipper last modified Jul 15, 2009 03:56 AM
Here we'll create a single form to insert data into related tables.

The following table relations will be covered by our form: 1:1, 1:n and m:n.


Let's use an example database to go through in this tutorial. It is a contact keeping database. Here are the tables and their relations:

Person |
1:1  | Info 
Person | 
1:n  | Telephone 
Person |
m:n  | Keyword 
Person |
m:n  | Donor

As you can see, Person will be our main table. I'll take you already know how to create these tables and relations, along with setting the foreign keys necessary and so on.

As such, you should probably know we'll need two extra tables to handle the many to many relations we are using in this example. We'll call them Person_has_Keyword and Person_has_Donor.


This will be the (simplified) layout:
TableFields
Person
IDperson
Name: VARCHAR
Birthday: DATE
Info
IDinfo
InfoText: TEXT
(FK)
Telephone
IDphone
PhoneType: VARCHAR
PhoneNumber: VARCHAR
(FK)

Keyword

IDkey
Keyword: VARCHAR (UNIQUE)

Donor

IDdonor
DonorName: VARCHAR (UNIQUE)

Person_has_Donor

Amount: DECIMAL
(FK)
(FK)


Person_has_Keyword  

(FK)
(FK)



Now on to create the form.

PloneFormGen makes it easy for us. You can add the fields any way you prefer, I created FieldSet Folders to group related fields, like the fields from the Person and Info tables. Add a hidden field for the IDperson (the main table) with a default value of -1, so we can use the same form for updating the data later. Try to keep all field names the same as the names of your database fields, so the scripting is easier. You can change their presented titles to whatever you want tho.

Birthday is a Date/Time field and InfoText is a Text Field. For the Telephone, we'll use a DataGrid Field with 2 columns, one for phone type and another for the number. You could set a default value for the phone type to say residencial, or office, for instance.


The Donors will also use a DataGrid Field with 2 columns: one for the donor name and the other for the amount donated.

We could use a DataGrid Field for the Keywords aswell, but let's have it different: add a simple String field to it, and instruct the users to separate the keywords with commas on the description of the field.

Form Layout




You should now have something similar to this.

Adapt it to your own preferred layout style at will.





click the image to enlarge


So we now have to wire this to actually do what we want, ie. add the input data to the database.