DB_Table Forms Tutorial
Описание
This page documents the use of the DB_Table class to create HTML_QuickForm form elements appropriate for the columns of a table, and to create entire data entry forms. DB_Table can use the column definitions to automatically create default form elements for you. Although your plain column definitions will do fine at first, you will want to customize the labels and options for your form elements. You can do so by adding 'qf_*' keys to your column definitions
Note: The underlying HTML_QuickForm package is a very powerful library with many options. While DB_Table automates away much of the complexity for simple forms, the full power of HTML_QuickForm can only be realized by combining the automatic element creation from DB_Table with custom-created HTML_QuickForm objects. DB_Table makes it easy to get started with HTML_QuickForm, but does not replace it.
Simple Form with Default Elements
Once you have defined your columns and instantiated an object, you can generate a complete HTML_QuickForm object using the getForm() method. If getForm() is called with no parameters, it will return a form with all of the $GuestBook object columns as input fields.
A default form with all columns
<?php
// [snip] create the GuestBook_Table object ($GuestBook)
// create the <classname>HTML_QuickForm</classname> object
$form =& $GuestBook->getForm(); // note the "=&" -- very important
// display the form
$form->display();
?>
Specifying Columns
To limit the fields you want to display, or to change the order, pass a sequential array of column names as the first parameter to getForm()
Specifying column names in getForm()
<?php
// [snip] create the Guesbook object ($GuestBook)
// only show the first name, last name, and email in the form
$cols = array('fname', 'lname', 'email');
// create the <classname>HTML_QuickForm</classname> object
$form =& $GuestBook->getForm($cols);
// display the form
$form->display();
?>
Add Buttons
Unfortunately, the form only has the input fields; it does not yet have "Submit" or "Reset" buttons, which are not automatically generated.
Adding "Submit" and "Reset" buttons with getForm()
<?php
// [snip] create the $GuestBook GuestBook_Table object
// create the HMTL_QuickForm object
$form =& $GuestBook->getForm($cols);
// add a "submit" button named "op" that says "Go!"
$form->addElement('submit', 'op', 'Go!');
// add a reset button
$form->addElement('reset');
// display the form
$form->display();
?>
Simple Form with Custom Elements
The basic form is nice, but it's very generic. It doesn't have descriptive labels for the input fields, all the fields are text boxes, and so on. This section shows you how to include form element properties along with your column definitions so that your forms are customized in a somewhat consistent fashion.
In every case you will modify the $col property by adding 'qf_*' keys and values.
- 'qf_label' (string) Adds a text label to the field
- 'qf_type' (string) Sets the input type (text, hidden, select, checkbox, etc.)
- 'qf_vals' (array) Sets list of values for select, radio, and checkbox elements
- 'qf_attrs' (array) Sets additional HTML attributes for the input element
- 'qf_opts' (array) Sets options for date elements (date, time, timestamp, jscalendar)
Element Label
When a column appears in a form, you can make sure the same label is always applied to it. Let's say we have a column called "other" defined as a 32-character string. We always want it to be labelled as "Other Information" in our forms; use 'qf_label' key like this:
Setting 'qf_label'
<?php
class GuestBook_Table extends DB_Table
{
var $col = array(
// ...
'example' => array(
// table column definition
'type' => 'varchar',
'size' => 32,
// form element definition
'qf_label' => 'Other Information'
)
);
}
?>
Element Type
By default, DB_Table will try to figure out what kind of form field input type to use for your column. Most column types translate into text fields, but there are some exceptions.
- Boolean columns become HTML_QuickForm 'advcheckbox' fields with values of 0 for not-checked and 1 for checked.
- CLOB columns become HTML_QuickForm 'textarea' fields
- Date columns become HTML_QuickForm 'date' select fields in 'Y-m-d' format.
- Time columns become HTML_QuickForm 'date' select fields in 'H:i:s' format.
- Timestamp columns become HTML_QuickForm 'date' select fields in 'Y-m-d H:i:s' format
To explicitly set the HTML_QuickForm element type for a column, rather than relying on the above defaults, you add a 'qf_type' element to your column definition. You can tell DB_Table to create any of several supported HTML_QuickForm element types by setting the 'qf_type' element to one of these string values:
- 'checkbox' for a single checkbox; maps to the 'advcheckbox' HTML_QuickForm type
- 'hidden' for a hidden element
- 'password' for a password text box
- 'radio' for a set of radio buttons
- 'select' for a select menu
- 'text' for a text box
- 'textarea' for a text area
- 'date' for a date selector; formats as 'Y-m-d'
- 'time' for a time selector; maps to 'date', formats as 'H:i:s'
- 'timestamp' for a timestamp selector; maps to 'date', formats as 'Y-m-d H:i:s'
If you use any other element name, DB_Table will attempt to map to the proper HTML_QuickForm element (thanks to Moritz Heidkamp for the patch), but it's not guaranteed to work.
In this example, we'll make the 'example' column a text field:
Setting an element type
<?php
class GuestBook_Table extends DB_Table
{
var $col = array(
// ...
'example' => array(
// table column definition
'type' => 'varchar',
'size' => 32,
// form element definition
'qf_label' => 'Other Information',
'qf_type' => 'text'
)
);
}
?>
Element Values
If your column form element is 'checkbox', 'radio', or 'select', you can set the values of the available choices for the form element. You do so via an 'sq_vals' element in the corresponding column definition.
Setting CheckBox Values
For a checkbox, use a sequential array of two elements: the first is the value if the box is not checked, and the second is the value if it is checked.
In this example, the checkbox values are 0 if not checked,and 1 if checked; these are the values that will be stored in the column.
<?php
class GuestBook_Table extends DB_Table
{
var $col = array(
// ...
'example' => array(
// table column definition
'type' => 'varchar',
'size' => 32,
// form element definition
'qf_label' => 'Other Information',
'qf_type' => 'text',
'qf_vals' => array(0, 1)
)
);
}
?>
Radio and Select Values
For radio buttons and select menus, use an associative array. Each array key is the value that will be stored in the column, and each array value is the text that will be displayed to the user.
This example creates a select menu with three possible values ('a', 'b', and 'c') and the corresponding labels:
<?php
class GuestBook_Table extends DB_Table
{
var $col = array(
// ...
'example' => array(
// table column definition
'type' => 'varchar',
'size' => 32,
// form element definition
'qf_label' => 'Other Information',
'qf_type' => 'text',
'qf_vals' => array(
'a' => 'This is the letter "a"',
'b' => 'I choose "b"',
'c' => 'No, "c" is always the right answer'
)
)
);
}
?>
Element HTML Attributes
If you like, you can add HTML attributes to the form element using the 'qf_attrs' keys. Attributes are assigned as key-value pairs in an associative array; the keys is the attribute name, and the value is the attribute value. For example, to set the number of rows and columns for a textarea element:
Setting rows and column number for a textarea
<?php
class GuestBook_Table extends DB_Table
{
var $col = array(
// ...
'example' => array(
// table column definition
'type' => 'varchar',
'size' => 32,
// form element definition
'qf_label' => 'Other Information',
'qf_type' => 'textarea',
'qf_attrs' => array(
'rows' => 24,
'cols' => 80
)
)
);
}
?>
DB_Table automatically adds a "maxlength" attribute to text and password elements based on the column size, so that users cannot type in values longer than the column allows.
Element Rules
HTML_QuickForm allows you to add validation rules to the input form. These rules are not the same as the DB_Table automated validations; the HTML_QuickForm rules apply only to the values as they relate to the form itself, not the values related to the table proper. This is an important distinction that will become apparent as you use HTML_QuickForm.
The available rules are:
- email - the form input must be an email address
- lettersonly -- the form nput must consist only of letters
- maxlength -- the form input cannot have more than this many characters
- maxlength -- the form input cannot have fewer than this many characters
- nonzero -- the form input must be greater than or less than zero
- nopunctuation -- the form input may not contain punctuation
- numeric -- the form input must be a number of some sort (no letters)
- regex -- the form input must match a regular expression
- required -- the form input is required to be filled (even with a single space)
DB_Table will automatically add HTML_QuickForm rules for you in most cases.
- If the column is required ('require' => true), then DB_Table will add a 'required' HTML_QuickForm rule.
- If the column is numeric ('smallint', 'integer', 'bigint', 'single', 'double', or 'timestep') then DB_Table will a 'numeric' HTML_QuickForm rule.
- If the column has a specific size ('size'), then DB_Table will add a 'maxlength' rule.
If you want to use a specific HTML_QuickForm rule for a column when that column appears in a form, set 'qf_rules' key to the name of the rule and set the value for that rule; in most cases, the value is an error message, but in some cases the value is a sequential array. You can add as many different rules as you like, but you can add only one of each type.
QuickForm Rules
<?php
class GuestBook_Table extends DB_Table
{
var $col = array(
// ...
'example1' => array(
// table column definition
'type' => 'integer',
// form element definition
'qf_label' => 'Information',
'qf_type' => 'text',
// a set of QuickForm rules
'qf_rules' => array(
'required' => 'This field is required.',
'numeric' => 'Please use only numbers, no letters.'
)
),
'example2' => array(
// table column definition
'type' => 'varchar',
'size' => 10,
// form element definition
'qf_label' => 'Something:',
'qf_type' => 'text',
// a set of QuickForm rules
'qf_rules' => array(
'minlength' => array('Minimum length is 6 characters.', 6),
'maxlength' => array('Maximum length is 10 characters.', 10),
'regex' => array(
'Must be only upper-case letters and underscores.',
'/^[A-Z_]+$/'
)
);
)
)
}
?>
HTML_QuickForm supports rules for groups and entire forms, but DB_Table does not automate these; you will need to add them to the form object yourself.
Setting Default Values
Sometimes you will want to populate your input form with default values, such as the current values from the database. Doing so is easy.
When you call getForm(), instead of passing a sequential array of column names, pass an associative array in which the key is the column name and the value is the column value.
Setting Default Values for Form Fields
<?php
// [snip] create the GuestBook_Table object ($GuestBook)
// Show only the first name, last name, and email in the form
// Provide default values for the form elements
$cols = array(
'fname' => 'Thomas',
'lname' => 'Anderson',
'email' => 'neo@matrix.net'
);
// create the HTML_QuickForm object
$form =& $GuestBook->getForm($cols);
// display the form
$form->display();
?>
Element Names as Array Keys
By default, when you call getForm(), the form elements are named for their columns. For example, the column 'fname' is called 'fname' in the form.
<!-- [snip] the beginning of the form --> <input type="text" name="fname" ... /> <!-- [snip] the end of the form -->
However, often you will want the form elements to be keys in any array instead of their own separate variables. This is particularly useful when you are going to use the values in a DB_Table insert() or update() call.
To do so, pass the name of an array as the second argument to getForm() (after the list of columns to use in the form). For example, if you want the column names to be keys in an array called 'new_row', do this:
Returning form values in an array
<?php
// [snip] create the $GuestBook object of class GuestBook_Table
// choose which columns to display in the form
$cols = array('fname', 'lname', 'email');
// create the HTML_QuickForm object, with elements
// named as part of an array called 'new_row'
$form = $GuestBook->getForm($cols, 'new_row');
// display the form
$form->display()
?>
Custom HTML_QuickForm Objects
Although the getForm() method supports all HTML_QuickForm parameters (such as the name of the form, the method, the action, and so on), you don't need to use DB_Table to create the entire form. If you like, you can create your own HTML_QuickForm object, and add DB_Table columns to it one-by-one or in groups.
DB_Table provides these methods to add automatically-defined elements to pre-existing HTML_QuickForm objects:
- addFormElements() to add one or more automatically-defined form element objects to a pre-existing HTML_QuickForm object, along with their associated DB_Table defined rules.
- getFormGroup() to get an HTML_QuickForm group array of automatically-defined element objects
- getFormElement() to get a single automatically defined element object.
Here are example uses of each:
Custom HTML Element
<?php
// [snip] Create the GuestBook_Table object $GuestBook
// load the class file and create a QuickForm object
require_once 'HTML/QuickForm.php';
$form =& new HTML_QuickForm();
// add one or more elements from the GuestBook
// object to the QuickForm object, along with
// the rules for those elements
$cols = array('email', 'signdate');
$GuestBook->addFormElements($form, $cols);
// add an element group of GuestBook columns
// to the QuickForm object (does not add rules)
$cols = array('fname', 'lname');
$group =& $GuestBook->getFormGroup($cols);
$form->addGroup($group);
// get back a single form element object with a
// custom name, then add it to the form
$col = 'id';
$name = 'new_row[id]';
$element =& $GuestBook->getFormElement($col, $name);
$form->addElement($element);
?>