Class TM::Apeform by Thiemo Mättig
Version 2004-04-30

A very abstract web form builder.

This class creates self repeating web forms - so called "Affenformulare" (ape forms) - in a very useful, easy way. The usage is not different from the creation, validation and processing of the form values that the user entered. Everything is done in a single script.

The class hides the access to POST and global variables and simply returns the submitted values. It offers an easy way to handle input errors (checking valid email adresses for example). It supports all usual form elements including radio buttons, select boxes, file upload fields and so on. It provides an own, tiny templating system, so you don't have to deal with HTML at all. It creates labels and access keys according to HTML 4 standard and returns XHTML compatible output. In addition you can add JavaScript handlers to any form element.

The class is optimized to be used with the minimum amount of source code. See display() for a tiny example.

Don't hesitate to report bugs or feature requests.

Variable Summary
id -- Unique identifier for the form and its elements.
maxLength -- Default maximum length of the input values.
size -- Default display size of the form elements.
templates -- The templates used to compile the form.
tmpDir -- Directory where to store uploaded files temporary.

Constructor Summary
Apeform -- Creates a new web form builder.

Method Summary
checkbox -- Adds one or more checkbox elements to the form.
display -- Outputs the form.
error -- Adds an error message to an element.
file -- Adds a file upload element to the form.
getName -- Gets the name of the element added last.
handler -- Adds a JavaScript event handler to the form or an element.
header -- Adds a header or subheading to the form.
hidden -- Adds a hidden input element to the form.
image -- Adds one or more image buttons to the form.
isValid -- Checks if the form is submitted error-free.
password -- Adds a password input element to the form.
radio -- Adds some radio buttons to the form.
select -- Adds a select element to the form.
staticText -- Adds a static text to the form.
submit -- Adds one or more submit buttons to the form.
text -- Adds a text input element to the form.
textarea -- Adds a text area to the form.
toHtml -- Compiles the form and returns the HTML output.

Variable Detail

id

Unique identifier for the form and its elements.

string $id

Defaults to "form". If set to something else, this will be used as prefix for every element name and id. This setting can also be changed when calling Apeform() or using an extended class.

maxLength

Default maximum length of the input values.

int $maxLength

Sets the maximum number of characters the user is able to type in text() and password() elements. Default is 255 characters. This setting can also be changed when calling Apeform() or using an extended class. It's also possible to set maxLength for single text() and password() elements.

size

Default display size of the form elements.

int $size

Default width is 40 characters. This can also be changed when calling Apeform() or using an extended class. It's also possible to set size for single elements when calling text() and so on.

templates

The templates used to compile the form.

array $templates

The class uses it's own tiny HTML templating system. This associative array contains all templates used to compile the form. It consists of up to five parts:

'form' will be used once as a container for the whole form. It may contain a table header and footer for example. 'input' will be used for each form element. It may contain a table row for example. 'label', 'error' and 'help' are optional. They may contain some special formating, line breaks etc. which should left out if help, error message or label is empty.

A basic example (default values are a little bit more complex):

$form->templates = array(
    'form' => "<table>{input}</table>",
    'header' => "<tr><th colspan=\"2\">{header}</th></tr>",
    'input' => "<tr><td>{label}</td><td>{input}</td></tr>",
    'label' => "{label}:",
    'error' => "<strong>{error}:</strong>");

tmpDir

Directory where to store uploaded files temporary.

string $tmpDir

It's importand to store uploaded files when using a file() element because PHP will remove any temporary file immediately. Set this to a temporary directory nearby your scripts using a relative path, e.g. "./temporary". Don't forget to enable writing access for this directory (using chmod).

Defaults to "/tmp" (default on Unix/Linux systems). If the directory doesn't exists, one of the TMP/TMPDIR environment variables will be used.

The tmpDir can also be changed using an extended class.

Constructor Detail

Apeform

Creates a new web form builder.

Apeform Apeform ( [ int maxLength [, int size [, string id [, bool magicQuotes]]]])

Class constructor of the web form builder. Returns a new Apeform object. All parameters are optional. They can also be set using an extended class. Default for maxLength is 255. Default for size is 40. Default for id is "form". Setting magicQuotes the user may disable or enable PHP's magic quotes behaviour manualy, independend what's set in the php.ini (see get_magic_quotes_gpc()). Defaults to the configurations default.

Method Detail

checkbox

Adds one or more checkbox elements to the form.

mixed checkbox ( string label [, string help [, mixed options [, mixed defaultValue]]])

If only one option is given or options is empty a single checkbox will be displayed. Returns a string in this case. If two or more options are given (see select() for some examples) it will return an array. The defaultValue also have to be an array in this case.

display

Outputs the form.

void display ( [ bool setFocus])

Displays the whole compiled form. Set setFocus to disable or enable the auto-focus feature (enabled by default if no id was set for the form, disabled otherwise). A slightly complex example:

<?php
require_once("Apeform.class.php");
$form = new Apeform();
$text = $form->text("Something");
if (! $text) $form->error("Please enter something");
$form->submit();
if ($form->isValid()) echo "Thank you!";
else $form->display();
?>

error

Adds an error message to an element.

void error ( [ string message [, int offset]])

Sets an error to the element added last by checkbox(), file(), password(), radio(), select(), submit(), text() or textarea(). Use a relative offset to add an error message to any previous element.

The label of the faulty element will be replaced by the error message (if present) and displayed using another template (if present). If error() was called one or more times, isValid() will return false.

file

Adds a file upload element to the form.

array file ( [ string label [, string help [, int size]]])

Adds a single file upload element to the form. Encryption type of the form will be set to "multipart/form-data" automaticaly. Returns all file information in an associative array. For example $file = $form->file(); returns $file['name'], $file['type'], $file['size'], $file['tmp_name'] and $file['error']. Additionaly, $file['unixname'] provides a noncritical file name without any spaces and special characters.

Unlike regular upload forms the file is not lost when the script ends. The file will be stored in the temporary directory specified by tmpDir or in the systems default TMP/TMPDIR. Use copy() to move the file anywhere, for example copy($file['tmp_name'], "target/" . $file['name']);. Don't use move_uploaded_file()!

If the file upload element got an error() the temporary file will be removed immediately. The garbage collection will remove any out-dated temporary file as soon as the next file is uploaded.

getName

Gets the name of the element added last.

string getName ( [ int offset])

Note: Normally, you don't need this. One of the main purposes of the class is to hide these element names.

This returns the internal element names "element0", "element1" and so on. Exception: hidden() may have a custom name. This may be useful to access $_POST variables or to create custom JavaScript handlers.

Use a relative offset to get the name of any previous added element. Returns false on error.

handler

Adds a JavaScript event handler to the form or an element.

void handler ( string event, string handler)

Puts the JavaScript handler to the form element added last. If no element was created yet or event is "onsubmit" the handler will be added to the form itself.

Some useful examples:

$form->handler("onfocus", "if (this.value == '...') this.value = '';");
$form->handler("onblur", "if (this.value == '') this.value = '...';");
$form->handler("onclick", "this.form.submit();");
$form->handler(
    "onsubmit",
    "if (this.elements['element0'].value == '') {
         alert('Please enter something!');
         return false;
     }");

Adds a header or subheading to the form.

string header ( string header)

This is the only element that uses the template 'header'.

hidden

Adds a hidden input element to the form.

string hidden ( [ string defaultValue [, string name]])

Adds a hidden element to the form. Returns the hidden value. If you need the value before hidden() was called, set a name. This is the only place you need to set a name for an element. This way you are able to fetch the hidden value using $_POST or $_REQUEST['elementName'].

image

Adds one or more image buttons to the form.

string image ( string src [, string help])

Warning! This method is EXPERIMENTAL. The behaviour of this method may change in a future release of this class.

isValid

Checks if the form is submitted error-free.

bool isValid ( void)

Returns true if the form was submitted already and no error has been set. If the form is displayed the first time, isValid() always returns false. If error() was called at least once it returns false too.

password

Adds a password input element to the form.

string password ( [ string label [, string help [, string defaultValue [, int maxLength [, int size]]]]])

Adds a password input element that works the same way like text(). The only difference is, if an error occurs the value will be removed (because the user can't see what he typed wrong).

radio

Adds some radio buttons to the form.

string radio ( string label, string help, mixed options [, string defaultValue])

Adds two or more radio buttons to the form. See select() for further explanation.

select

Adds a select element to the form.

string select ( string label, string help, mixed options [, string defaultValue [, int size]])

Adds a box to the form to select a value out of two or more values. This is almost similar to radio() except for the way it is rendered.

The options may be an associative array, for example array("a" => "Option A", "b" => "Option B"). The values of this array will be displayed, the keys will be submitted. For example, the user selects "Option B" so a "b" will be returned by select(). The options can also be a string, for example "Option A|Option B". This way the displayed and submitted values will be always the same, for example "Option B".

Set defaultValue to one of the array keys to select an option by default. Leave it empty to select nothing by default.

The size isn't the width but the number of rows of the element. Default is one row.

Returns defaultValue if the form is displayed the first time. After this it returns the array key of the selected option or an empty string if nothing was selected. Use the $ref = &$form->select(); syntax (note the &) to return the value by reference.

staticText

Adds a static text to the form.

string staticText ( [ string label [, string help [, string defaultValue]]])

For example, display a text element first. If the user entered a valid value, replace the text with a staticText element. Example:

$form = new Apeform();
$form->text("Text");
if (! $form->isValid()) $form->text("Static");
else $form->staticText("Static");
$form->submit();
$form->display();

submit

Adds one or more submit buttons to the form.

string submit ( [ mixed value [, string help]])

Adds some submit buttons to the form. The value may be a simple string to create a single button. It may be an array to create multiple buttons. It's also possible to use a string for multiple buttons, for example "Button A|Button B". Returns the value of the button the user pressed.

text

Adds a text input element to the form.

string text ( [ string label [, string help [, string defaultValue [, int maxLength [, int size]]]]])

Adds a single line input box to the form. All the arguments may be left out in order from right to left.

Use HTML tags for an "<u>u</u>nderlined" character in the label to set an access key for this element. Pressing Alt+character will focus this element later. Keep this in mind, this works for almost all elements.

If help is set to "Help\tUnit" for example, the text "Unit" will be displayed behind the input field. This works for all element types but makes sense only for a few of them.

Returns defaultValue if the form is displayed the first time. After this it returns the value the user entered and submitted. Use the $ref = &$form->text(); syntax (note the &) to return the value by reference. This way you are able to change the value displayed in the form (e.g. make it upper case).

textarea

Adds a text area to the form.

string textarea ( [ string label [, string help [, string defaultValue [, int rows [, int cols [, mixed wrap]]]]]])

Adds a multi line input box to the form. Works similar to text().

To change the height of the area set the number of rows. Default is 3. Default for cols is 40 (see size). Default for wrap is "virtual". Other possible values are "off" or false.

toHtml

Compiles the form and returns the HTML output.

string toHtml ( [ bool setFocus])

Compiles the whole form using default or user defined templates and returns the resulting HTML code as a string. Example:

echo $form->toHtml();

Documentation generated by TM::PHPDoc