dbForm PHP Project
dbForm 0.9.2 Manual
Release Date: 27 May 2004
Note: For the lastest manual be sure to download and look for manual.txt

dbForm is a PHP class that will create a Web Form for a database table and handles all processing of the form including validation of data, inserts, updates and deletes. Very customisable and flexible. Uses ADODB to connect to any database. Uses a simple Template to display the form.

How do you use dbForm?

dbForm comes in 2 parts, the code and the template. We will look at them now but they can be performed in either order.

1. Setting up the code.

Firstly we need to include the necessary files

include_once("path/to/dbForm/formFields.inc");
include_once(
"path/to/dbForm/template.inc");
include_once(
"path/to/dbForm/dbForm.inc");

It is important that dbForm.inc is the last item included because it extends template.inc and uses formFields.inc.

You will also need to create an ADODB connection. (See ADODB website http://php.weblogs.com/ADOdb for more info)

include_once("path/to/adodb/adodb.inc.php");
$conn = &ADONewConnection("mysql");
$conn->Connect("localhost", "username", "password", "dbname");
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;

Note: this is an example of connecting to mysql. See the ADODB manuals for more details.

You are now ready to create the form.

We are going to use a table called Person as the example
We can assume that the person table is as follows
CREATE TABLE `person` (
`personid` int(11) NOT NULL auto_increment,
`firstname` varchar(50) NOT NULL default '',
`lastname` varchar(50) default NULL,
`username` varchar(20) NOT NULL default '',
`password` varchar(32) NOT NULL default '',
`email` varchar(255) NOT NULL default '',
`created` datetime NOT NULL default '0000-00-00 00:00:00',
`lastlogin` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`personid`)
);

To create a form for the person table
$dbForm = new dbForm("Person", $conn, "person");

This creates a form called "Person" using the ADODB connection $conn for the table "person". At this point the class will have detected all of the fields in person and created fields in the class to match.

We now need to set the search field.
$dbForm->setSearchField("personid", "select personid, lastname, firstname from person", ", ");

This will create a search list for the form. "personid" is identified as the key to use for the search, then follows the query to populate the search list.
The search list query must select the kiey field first, then any other fields to be displayed.
Lastly ", " is the glue to link all of the display fields.
So in this example the search list will display "lastname, firstname" for each person and the "personid" field will be set to be hidden.

You could now just process and display the form but if you need to you can change some of the fields.

For this form we would want the password field to be handled properly so we will set it to a password field type.

$dbForm->changeFieldType("password","password");

This says change the field "password" to a password field.
Password fields will not have their actualy value in the form.
For a password field you can also say that you want to store the password as an MD5 hash buy using the following:

$dbForm->hashPasswords=true;

Next if we want to change how the date fields are displayed we can do that also.

$dbForm->changeFieldType("created", "date");

This says that the field "created" should be displayed as a "date".
By default from the table description "create" would be set to a "datetime" field.
There are 3 date types that dbForm can display
Date - displays day month year selectors
Time - display hour minutes seconds selectors
DateTime - displays day month year hour minutes seconds selectors
so the above example will change from datetime to date.

Now if we decide we don't want to see the lastlogin field we can remove it.

$dbForm->removeField("lastlogin");

We don't want to make any more changes to the form now so we will process.

$dbForm->processForm();

This will process any form actions. dbForm works by calling itself on each action and the processForm method will handle this processing. See the details of all methods later to see how to override the processing functions.

Now we need to set the template file we are going to use.
(See section 2 for details about creating a template file).
Note: As of dbForm 0.8.1 template files can be set before or after processForm.

$dbForm->setTemplateFile("testform.tpl");

This simply says that we are going to use the file "testform.tpl" as the template for this form.

If there are any replacements to be made in the template you do them now.

$dbForm->replace("Color", "#FF0000");

This replaces any {Color} tags with #FF0000. (See section 2 for more).

And now we are ready to display the form.

$dbForm->displayForm();

All done.

As a final summary here is the php script in full
<?php
// include necessary files
include_once("path/to/dbForm/formFields.inc");
include_once(
"path/to/dbForm/template.inc");
include_once(
"path/to/dbForm/dbForm.inc");

// create database connection
include_once("path/to/adodb/adodb.inc.php");
$conn = &ADONewConnection("mysql");
$conn->Connect("localhost", "username", "password", "dbname");
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;

// create dbForm class for person table
$dbForm = new dbForm("Person", $conn, "person");

// set the search field
$dbForm->setSearchField("personid", "select personid, lastname, firstname from person", ", ");

// change the password field and make it a hash
$dbForm->changeFieldType("password","password");
$dbForm->hashPasswords=true;

// change the created field
$dbForm->changeFieldType("created", "date");

// remove the lastlogin field
$dbForm->removeField("lastlogin");

// Process the form
$dbForm->processForm();

// set the template and do any replacements
$dbForm->setTemplateFile("testform.tpl");
$dbForm->replace("Color", "#FF0000");

// display the form
$dbForm->displayForm();

// end
?>

Note: this was not a complete example of all of the methods available so please make sure you look at the end of this file for all of the method descriptions.


2. Creating the template files

The Templates are simply html files that have some special tags in them.
Rather than the tags being enclosed by < and > like normal html tags, these tags are enclosed by curly braces { }.
For simple replacements use {var_name}, with $class->replace("var_name","replacement"); used in the code.

There are also a number of preset tags that can be used with the form to display fields etc.
They are as follows:

{:template=""}
Includes another template inside the current one.


{:action=""}
{:end action}
Includes a section of html only if the current form action matches the actions in the list. The action list is a comma seperated list of all of the actions e.g. "select,update".
The actions match buttons. See the method list for details of the default buttons and adding/removing buttons.


{:each field=""}
Loads a new template file for each field on the form


{:each field}
{:end field}
Repeats the code between the tags for each field on the form

{:fieldname}
Displays the name of the field. Only usable inside {:each field} tags
{:field}
Displays the field. Only usable inside {:each field} tags
Can contain attributes that will be applied to each field
e.g. {:field style="color: blue;"} will add the attribute style="color: blue;" to each field


{:field=""}
Displays the selected Field
Can contain attributes that will be applied to the field
e.g. {:field="firstname" style="color: blue;"} will add the attribute style="color: blue;" to firstname field


{:#fields}
Returns the number of visible fields


{:each button=""}
Loads a new template file for each button on the form


{:each button}
{:end button}
Repeats the code between the tags for each button on the form

{:button}
Display the button. Only usable inside {:each button} tags
Can contain attributes that will be applied to each button
e.g. {:button style="color: blue;"} will add the attribute style="color: blue;" to each button


{:button=""}
Displays the selected button
Can contain attributes that will be applied to the button
e.g. {:button="update" style="color: blue;"} will add the attribute style="color: blue;" to update button


{:#buttons}
Returns the number of buttons


{:hidden}
Displays all of the hidden fields
Can contain attributes that will be applied to each hidden field
e.g. {:hidden style="color: blue;"} will add the attribute style="color: blue;" to each hidden field


{:formname}
Displays the name setup in the initial creation of the form


{:form}
Displays the opening form tag. You will have to put the closing tag yourself.
Can contain attributes that will be applied to the form tag
e.g. {:form style="color: blue;"} will add the attribute style="color: blue;" to the form tag


{:status}
Display any status messages from the form.

See testform.tpl as an example of how these tags can be used.
Note: Template files do NOT have to have the tpl extension.


3. dbForm public Method and Property list.

Note: This is the list of the properties and methods that were designed to be public.
You can call some of the private properties and methods if you want but they may not work as you expect.

GLOBAL Variables.

$dbMinYear
Global variable only used with dbDateTime class.
Specifies the minimum year that will be displayed in a date/datetime list.
Also used as the year of a timestamp if no year is set.
Must be set before displayForm().
Default: 1900


$dbMaxYear
Global variable only used with dbDateTime class.
Specifies the maximum year that will be displayed in a date/datetime list.
Must be set before displayForm().
Default: 2100

Properties.

ver
Contains the current version number of dbForm.
Change at your own risk but include this in any support requests


alwaysUpdate
Boolean flag for whether the record should always be updated on an action.
Must be set before processForm() is called.
Default: false


hashPasswords
Boolean flag for whether passwords should be MD5 Hashed before they are stored in the database.
Must be set before processForm() is called.
Default: false


validateFields
Boolean flag for using field validation.
Must be set before processForm() is called.
Default: false


forceUpdateNulls
Boolean flag to force updating of null fields
Must be set before processForm to be effective
Suggested by Keith Powers
Default: true


magicQuote
Boolean flag to handle magic Quoting of GET/POST/COOKIE values
Default: get_magic_quotes_gpc() (See PHP manual)

Methods.

dbForm($name, $conn=null, $table=null, $method='POST', $action=null, $target='_self', $attributes=null)
Constructor for the class.
Note that form does not require anything but a name.
$conn must be an ADODB connection object.
$table is the table to base the form on.
$method is the form action method POST or GET only.
$action is the form action. Defaults to self.
$target is the form target. Defaults to _self.
$attributes is an array of form attributes.

setAttributes($attributes)
Sets the attributes of a form.
$attributes is an array of form attributes.
e.g. setAttributes(array("onsubmit"=>"return false"));
This will add the attribute onsubmit="return false" to the form tag.
Must be set before displayForm() is called.

setSequence($sequence)
Sets the name of the ADODB sequence to use for the table.
See the ADODB website for information about ADODB Sequences.
Must be set before processForm() is called.

setSequenceFunction($function)
Sets the Sequence Function to use for the table in the form
Function will be called on insert to determine the new primary key for the table
Really only useful if you need to produce a non standard key that cannot be generated by a sequence
The specified function is passed the following paramters.
&$conn
The database connection that can be used to generate the new sequence value if required.
$table
The table that the form is built for.
$searchField
The field used to search by. Set by the setSearchField() method.

addField($name, $type = "hidden", $dbType = null, $attributes = null)
Adds a field to the form.
$name is the name of the new field to add. If $name is the same as an existing field then it is overwritten.
$type is the type of the new form. See changeFieldType for the list of types.
$dbType is the meta type from ADODB of the field. Not necessary.
$attributes is any attributes of the field. See setAttributes for example.
Must be called before processForm().

setFieldTitle($field, $title)
Sets the title for a field.
If no title is set the fieldname will be displayed.
$field is the field to set the title for.
$title is the title to use for the field.
Must be called before processForm().

setFieldTitles($titlesArray)
Sets the title for many fields.
$titlesArray is an associative array of fields and their title
i.e.
$titlesArray["lastname"]="Lastname";
$titlesArray["firstname"]="Firstname";
$titlesArray["lastlogin"]="Last Login";
Must be called before processForm().

setFieldAttributes($fieldName, $attributes)
Adds some attributes to a field.
$fieldName is the name of the field.
$attributes is the array of field attributes. See setAttributes for example.
Note: you can hardcode field values using this function but they may be overwritten upon call to processForm.
Must be called before processForm().

setFieldMaxLength($fieldName, $length=null)
Sets the maximum length for a field.
Set automatically during loading of dbForm unless no table is set.
Must be called before processForm().

setFieldNotNull($fieldName, $notNull=true)
Sets the not null property of the field.
Set automatically during loading of dbForm unless no table is set.
Must be called before processForm().

setAllFieldsAttributes($attributes)
Adds some attributes to all fields.
$attributes is the array of field attributes. See setAttributes for example.
Note: you can hardcode field values using this function but they may be overwritten upon call to processForm.
Must be called before processForm().

changeFieldType($field, $type="hidden")
Changes the type of a field
$field is the name of the field to change
$type is the field type to change to.
Must be called before processForm().
Field types are as follows:
hidden
Hidden field on form
text
standard text field
textarea
standard text area field
password
password field. fields value will not be shown
select
standard select field
checkbox
standard checkbox field
radio
standard radio field
Not available at this time. Use checkbox or select instead.
button
standard button
submit
standard submit button
date
creates day, month, year selection lists
time
creates hour, minute, second selection lists
datetime
creates day, month, year, hour, minute, second selection list
display
displays the value of the field as text
select-display
displays the selected value of a select list as text
Note: There are methods to create submit and checkboxes

orderFields($orderArray)
Orders the fields to be displayed
$orderArray is an array of the fields in the order to display.
i.e. orderButtons(array("select","delete","update");
If any field is not in the array will be added to the end of the order.
Must be called before processForm().

removeField($name, $replace="")
Removes the field from the form
$name is the name of the field to remove
$replace is the text to replace the buttons with.
Must be called before processForm().

addButton($name, $title, $type="submit")
Adds a new buttons to the list.
$name is the name of the button, which then corresponds to its action.
$title is the title that appears on the button when it is displayed.
$type of the button to create. Valid types are submit, image or button.
Must be called before processForm().

setButtonAttributes($button, $attributes)
Set the attributes of a button.
$button is the name of the button to set attributes for.
$attributes is the array of field attributes. See setAttributes for example.
Must be called before processForm().

setAllButtonsAttributes($attributes)
Sets the attributes for all buttons.
$attributes is the array of field attributes. See setAttributes for example.
Must be called before processForm().

changeButtonType($name, $type="submit")
Sets the type of the button
$name is the name of the button to set.
$type is the type of button to set.
Must be called before processForm().

removeButton($name, $replace="")
Removes the named button from the group of buttons.
$name is the name of the button to remove.
$replace is the text to replace the buttons with.
Must be called before processForm().

clearButtons($replace="")
Clears all of the buttons.
$replace is the text to replace the buttons with.
By default the following buttons are created:
  • Select
  • New
  • Insert
  • Cancel
  • Update
  • Delete
Must be called before processForm().

orderButtons($orderArray)
Orders the buttons for display.
Only of uses if the buttons are not displayed by name.
$orderArray is an array of button names indexed by integer
See orderFields for example of an order array.
If any button not in the array will be added to the end of the order.
Must be called before processForm().

setSearchField($name, $query, $glue=" ", $defaultText=null, $autoSelect=false)
Required if not using setSearchFunction.
Sets the field used for the search list
$name is the name of the field. Should be the primary key of the table.
$query is the query used to populate the search list. Must have the $name field as the first field in the query.
$glue is the glue used to concatenate any fields for display.
i.e. if $query = "select personid, firstname, lastname" and $glue=" - " then the list will contain "firstname - lastname" for each record.
$defaultText is the text to display for a default item in the selection list.
$autoSelect will select the record when selected in the list. Removes the select button.
Must be called before processForm().

setSearchFunction($name, $function, $autoSelect=false)
Required if not using setSearchField.
Sets the field used for the search list and the function used to populate the list.
$name is the name of the field. Should be the primary key of the table.
$function is the name of the function to call to populate the list.
$autoSelect will select the record when selected in the list. Removes the select button.

Search functions will be passed the following parameters.
$value is the value of the current selected item.

Search functions should return an array of items in the following format:
$options[0]["value"]=1
$options[0]["text"]="Some Text"
$options[0]["selected"]=true // only if $value = 1
$options[0][any other attributes]=something;

setFilterQuery($field, $filterField, $filterQuery, $filterReplace, $glue=" ", $defaultText=null)
Sets a filter query for a select list.

The filter query will be run first and the data displayed in the search list in an attempt to limit the search records displayed.
Uses similar parameters to setSearchField.
Currently only the search field can be filtered.
NOTE: Hidden fields are added to the form to help with filter processing.
$field is the field to filter.
$filterField is the field in the search query to filter by.
$filterQuery is the query to display the filter list.
$filterReplace is the text to replace in the search query when filtering.
$glue is the glue used to concatenate any fields for display.
$defaultText is the text to display for a default item in the filtered list.

See the Filter Query Demo page for more information.
Must be called before processForm().

setFilterGroup($field, $filterField, $filterGroup, $filterReplace, $defaultText=null)
Sets a filter group for a select list.

The filter query will be run first and the data displayed in the search list in an attempt to limit the search records displayed.
Builds the filter list based on a array of filter groups.
Currently only the earch field can be filtered.
NOTE: Hidden fields are added to the form to help with filter processing.
$field is the field to filter.
$filterField is the field in the search query to filter by.
$filterGroup is an array of filter groups. i.e. array('A..N','O..Z')
$filterReplace is the text to replace in the search query when filtering.
$defaultText is the text to display for a default item in the filtered list.

See the Filter Group Demo page for more information.
Must be called before processForm().

setFilterPaging($field, $pageSize, $defaultText=null)
Sets a filter Page for a select list.

The filter query will be run first and the data displayed in the search list in an attempt to limit the search records displayed.
Build filter by creating groups of X records.
Uses SELECT LIMIT queries or the ADODB simulated equivilent.
Currently only the earch field can be filtered.
NOTE: Hidden fields are added to the form to help with filter processing.
$field is the field to filter.
$pageSize is the number of records to appear in each filtered page.
$defaultText is the text to display for a default item in the filtered list.

See the Filter Paging Demo page for more information.
Must be called before processForm().

setCheckbox($field, $checkedValue = true, $uncheckedValue = false)
Sets the named field to a checkbox with the following values
$field is the name of the field
$checkedValue is the value to store in the database if checked
$uncheckedValue is the value to store in the database if unchecked
Must be called before processForm().

setProcessingFunction($action, $function=null)
Sets the user defined function to use to process an action.
$action is the action to set the function for.
$function is the name of the function to call.
Must be set before processForm().

Processing functions will be passed the following parameters.
&$conn
The database connection that can be used to process the action.
$table
The table that the form is built for.
$httpvars
Array of the _GET or _POST variables passed to the form.
$httpfiles
Array of the _FILES variables passed to the form. Used for file upload processing.
$searchField
The field used to search by. Set by the setSearchField() method.
$searchid
The value returned from the search field.
$action
The form action to process.

These parameters are general enough that it is possible to create
a single function to process all form actions if desired.

Processing functions should return an array of values for the fields
If no values are needed return an empty array
e.g.
$returnValues["personid"]["value"]=2;
$returnValues["lastname"]["value"]="Smith";
$returnValues["firstname"]["value"]="John";

setActionStatusMsg($action, $status=null)
Sets the status message for a given action.
Allows setting of the default status message to use for a specified action.
Note: Does not validate that the action is possible. i.e. actions usually equate to button names
but this will NOT validate that a button of that name exists because to do so would not enable
setting of the "null" action status.
Also means that status messages could be set before the buttons are created.
Must be set before processForm().

setStatusMsg($status=null)
Sets the current Status Message
Hardcodes the status message reguardless of the current action.
Can be called at any time.

getFormAction()
Returns the form action based on the parameters passed.
Looks at the requesttypes passed and sets the _formAction property and returns this as a value.
Can be used to selectively create parts of the form depending on the action.
Note: If called before all buttons are added then it may not return the correct action.
Defaults to dbform_null.

processForm()
Required.
Function that processes the form based on the action (button) selected.
Calls default action functions or those functions set in setProcessingFunction().
Must be called before displayForm().

getSelectValues($name, $query, $fieldGlue=" ", $defaultText=null)
Required for any select fields except search field
Function that populates a Select list from a query.
$name is the name of the field.
$query is the query to populate the select list.
$fieldGlue is the glue to concatinate any display fields.
$defaultText is the text to display for a default item in the selection list.
See setSearchField for example.
Must be called after processForm().

getSelectFunction($name, $function)
Required for any select fields if not using getSelectValues.
Function that populates a Select list from a query.
$name is the name of the field.
$function is the name of the function to call.

Select functions will be passed the following parameters.
$value is the value of the current selected item.

Select functions should return an array of items in the following format:
$options[0]["value"]=1
$options[0]["text"]="Some Text"
$options[0]["selected"]=true // only if $value = 1
$options[0][any other attributes]=something;

setTemplateFile($templatefile)
Required.
Sets the template file to be used for displaying the form.
$templatefile is the location of the template file.
Pre-parses the template to load any sub-templates.
Every form must have a template or it cannot be displayed.
As of dbForm 0.8.1 can be set before or after processForm.

replace($tag, $value=null)
Replaces any replacement tags in the template with the indicated value.
$tag is the name of the tag, without the braces i.e. $tag = "hello" replace {hello}
$value is the value to replace the tag.

processTemplate()
Required if not using processTemplate().
Returns the HTML of the processed Template file
Must be called after processForm().

displayForm()
Required.
Displays the form using the template set previously.
Must be called after processForm().

Advanced Hints and Tips (requires dbForm 0.8.1+)

dbForm can do much more than you might expect if you think creatively.
Here are some of the things it is known that dbForm can do and some brief words about how to achieve them.

1. Serializing

You can serialize the dbForm class and store it anywhere you like, a session variable, a file, a database.
This enables you to cut down the processing time (as small as it already is).
During the sleep phase the class will store and serialise all information about the structure of the form including the following:

  • table
  • form attributes
  • sequence
  • fields
  • field order
  • buttons
  • searchfield
  • processing function names
  • a pre-parsed version of the template

The pre-parsed version of the template contains all of the template files but none of the other processing of the template.

Example
include_once("path/to/dbForm/formFields.inc");
include_once(
"path/to/dbForm/template.inc");
include_once(
"path/to/dbForm/dbForm.inc");
include_once("path/to/adodb/adodb.inc.php");
$conn = &ADONewConnection("mysql");
$conn->Connect("localhost", "username", "password", "dbname");
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
session_start();
if (isset($_SESSION["dbForm"])) {

$dbForm = unserialize($_SESSION["dbForm"]);
} else {
$dbForm = new dbForm("Person", $conn, "person");
$dbForm->setSearchField("personid", "select personid, lastname, firstname from person", ", ");
$dbForm->changeFieldType("password","password");
$dbForm->hashPasswords=true;
$dbForm->changeFieldType("created", "date");
$dbForm->removeField("lastlogin");
$dbForm->setTemplateFile("testform.tpl");
$_SESSION["dbForm"]=serialize($dbForm);
}
$dbForm->processForm();
$dbForm->replace("Color", "#FF0000");
$dbForm->displayForm();

Note:
If the dbForm element does not exist in the session then the class is setup as per usual and then stored in the session
If it does then it is retrieved from the session
The template file can now be set before processing the form.
The code from processForm is the same as usual.

2. Advanced Templates

You can now include attributes in certain template tags and these attributes will be included in the resulting html
The following template elements can contain attributes

{:field}
{:field=""}
{:button}
{:button=""}
{:hidden}
{:form}

No other template tags can include extra attributes, and if they do they will not be processed.
See the demo.tpl file included with the release for an example of this.


I hope this manual covers everything that is need to use dbForm.
If not drop me an email and let me know.
Thanks
Tony Blair
tonanbarbarian@hotmail.com