n. 1. the inherit form in every MySQL table. 2. the php script that makes it happen.

Support This Project

Documentation for Formitable 1.5

Description

Formitable is a PHP class used to create HTML forms from MySQL database tables. The resulting forms are completely customizable and the data is automatically inserted into the database upon submisssion. Formitable can also be used to edit existing database records.

Working with Multiple Database Tables

Starting with version 1.5 Formitable supports building forms from and inserting data into multiple database tables. This has been the single most commonly requested feature since Formitable started. Multi-table support is enabled by passing an array of table names in the constructor. The returned Formitable object is referred to as the "root".

The root contains a Formitable "node" for each table passed in the constructor. All methods that accept a field name support "dot syntax" (tableName.fieldName) to configure fields for specific tables. A few methods require dot syntax. Many methods also support passing the field name without a table in which case the method will be applied to all tables passed in the constructor. Any further considerations for individual methods are noted below.

Legend for Multi-form Method Behavior

Each of the methods has a particular behavior when Formitable is instantiated with multiple tables. Those behaviors are noted by the following letters.

Description
aMethod can be called by the root or node with no difference in behavior.
lMethod can be called by the root or node. When called by the root the method will be applied to all tables and will return an array of results unless dot syntax is used.
fMethod can be called by the root or node. When called by the root a table name must be supplied using dot syntax.
nMethod must be called by a node.
rMethod must be called by the root.

Summary of Public Methods

Legend

return type
method
type arguments
[type optional arguments]
MySQL syntax
html

Formitable object Formitable (resource $connection, str $database, str/array $table)
Description: The Formitable constructor.
Parameters: connection is a resource as returned by mysql_connect, either as a variable or passed directly. database is the database name. table is the table name, or an array of tables for a multi-table form (see notes on multi-table support for the latter.

void allowField (str $fieldName [, str $from *])
Description: Adds a field to the form signature, allowing it to be submitted and inserted into the table. Use this method when you want to include an arbitrary field in the database query when it was not output by Formitable. This method is only necessary when using encryption.
Parameters: fieldName is the form input name. from allows one field value to be used in another field upon submission, even if the field is in another table.
Notes: This method is only necessary when using encryption and you want to allow an arbitrary field to be submitted. It is also useful to allow the value of one field to be submitted for another.
Multi-table Notes: The from parameter requires dot syntax even if the field is in the same table.

void closeForm ([str $submitValue="Submit" [, str $attr="" [, str $resetValue="Reset Form" [, bool $printReset=true [, bool $closeForm=true ]]]])
Description: Closes the form and prints the hidden input "pkey" if a record has been retrieved using getRecord and the page value if using multiPage. It is recommended that you use setEncryptionKey to encrypt the value of "pkey".
Parameters: submitValue is the submit button text, use "image:path/to/image.gif" for an image type submit. attr is any attributes you want to add to the submit button. resetValue is the reset button text. printReset determines whether or not to output the reset button. closeForm determines whether or not to output the closing form tag </form>, this can be useful when you want to include extra form fields after the submit or include multiple submits.
Multi-table Notes: This method should only be called by the root.

str decrypt (str $value)
Description: Decrypts a value using the RC4 cipher.
Parameters: The value to decrypt.
Notes: An encryption key must be set first using setEncryptionKey.

str encrypt (str $value)
Description: Encrypts a value using the RC4 cipher.
Parameters: The value to encrypt.
Notes: An encryption key must be set first using setEncryptionKey.

void forceType (str $fieldName, str $inputType)
Description: Forces a form field to an explicit input type regardless of size.
Parameters: The name of the field and the html input type respectively. Valid field/input types are as follows:
    for enum field -"select" or "radio"
    for set field - "multiselect" or "checkbox"
    for string or blob field - "text", "textarea", "password" or "file"
Notes: All field types can also be forced as "hidden" to output a hidden input. A hidden value is also encrypted when using setEncryptionKey. Input types other than those above are ignored.

bool forceTypes (array $fieldNames[], array $inputTypes[])
Description: Same as above but the parameters are arrays.
Returns: False if the arrays are different sizes, True otherwise.

str getFieldDefault (str $fieldName)
Description: Returns a field's default MySQL value or false when no default is available.
Parameters: The name of the field.
Multi-table Notes: The fieldName parameter requires dot syntax if called from the root.

str getFieldLabel (str $fieldName)
Description: Returns a field's label, either as was set by labelField or by generating it from the field name by making the first letters uppercase and replacing underscores (_) with spaces (ex. my_field becomes 'My Field'.)
Parameters: The name of the field.
Multi-table Notes: The fieldName parameter requires dot syntax.

bool/str getFieldValue (str $fieldName)
Description: Get a field's value from an retrieved record or POST. This is useful for testing a value before outputting it or performing other value based logic.
Parameters: The name of the field.
Returns: The field's value or false if invalid.
Notes: Call getRecord first.
Multi-table Notes: The fieldName parameter requires dot syntax.

void getLabels (str $fieldName, str $tableName [, str $tableKey = "ID" [, str $tableValue = "name" ]])
Description: Retrieves records from another table to be used as labels for enum or set field types.
Parameters: fieldName is the field to get labels for and must be of either the enum or set data types. Any other type will be ignored. tableName is a table in the same database that stores the label/value pairs. tableValue is the name of the field in the table tableName containing the label displayed to the user. tableKey is the unique identifier/primary key in the table tableName that will be used as the input value. The tableKey values must correspond to valid values in the enum or set.
Notes: Use the default values when designing your table to save yourself a bit of code.

bool getRecord (str $id)
Description: Queries the table for a record to output as the input value for each field in the form. Used to update records.
Parameters: The primary key value of the record to retrieve.
Returns: True if a single record was retrieved successfully, false otherwise.
Notes: You must call setPrimaryKey first.

int/bool getPrimaryKey ()
Description: Returns the primary key from the last INSERT or UPDATE.
Returns: An integer id of the last affected record, or false on error.
Notes: The primary key must have the AUTO_INCREMENT attribute.

void hideField (str $fieldName)
Description: Omits a field from HTML output.
Parameters: The name of the field.
Notes: To output a field of type hidden use forceType.

void hideFields (array $fieldNames[])
Description: Same as above but the parameter is an array of names.

void labelField (str $fieldName, str $fieldLabel)
Description: Sets a fieldName's input label text to fieldLabel for output.
Notes: If no custom label is provided using labelField(s) or getLabels, the label will be generated from the field name by making the first letter uppercase and replacing underscores (_) with spaces (ex. my_field becomes 'My Field'.)

bool labelFields (array $fieldNames[], str $fieldLabels[])
Description: Same as above but the parameters are arrays.
Returns: False if the arrays are different sizes, True otherwise.

void multiPage (str $step [, str $buttonValue="Continue" ])
Description: Outputs a hidden field that enables the functionality of a multi page form.
Parameters: The page step ("start" for the first page, "next" for intermediate pages, and "end" for the last page), and optional button value.
Notes: See examples for further details on pagination. Also see setEncryptionKey.
Multi-table Notes: This method can only be called by the root.

void normalizedField ( str $fieldName, str $tableName [, str $tableKey = "ID" [, str $tableValue = "name" [, str $orderBy = "value ASC" [, str $whereClause = "1" ]]]])
Description: Retrieves records from another table to be used as label/value pairs for the input types of select, radio, and checkbox. Optional parameters are used to customize the query.
Parameters: fieldName is the field to get values for and must be of either the enum, set, or int data types. Any other type will be ignored. tableName is a table in the same database that stores the label/value pairs. tableValue is the name of the field in the table tableName containing the label displayed to the user. tableKey is the unique identifier/primary key in the table tableName that will be used as the input value. orderBy is the order clause used to SELECT record from tableName. whereClause is the where clause used in the SELECT statement.
Notes: When specifying the orderBy and/or whereClause parameters use "pkey" and "value" to reference tableKey and tableValue respectively.

void openForm ([str $attr="" [, $autoSubmit=true]])
Description: Opens the form tag or submits the form if pkey is set in POST.
Parameters: attr are extra attributes to include inside the closing bracket of the form tag, useful for client side scripts, styles, and a custom action. autoSubmit determines whether or not to insert/update the record automatically upon submission. action is deprecated in favor of including action in attr.
Multi-table Notes: This method can only be called by the root.

int printField (str $fieldName [, str $attributes="" [, bool $verify=false ]])
Description: Outputs a field by name.
Parameters: The field's name, optional extra attributes to include inside the closing bracket of the input tag (useful javascript, ids, classes etc.), and an optional flag to output the field as a verification field (see notes below).
Returns: 1 if fieldName is valid, 0 otherwise.
Notes: Set verify to true to output an input field that has the same settings as fieldName, but with a unique name. This tells Formitable to compare the two fields when the form is submitted to make sure they contain the same values, otherwise validation will fail. This functionality is commonly used with passwords and email addresses.

void printForm ()
Description: Outputs the entire form.
Notes: To customize your form layout use printField along with openForm and closeForm, or use printFromTemplate.
Multi-table Notes: This method should only be called by the root.

bool/str printFromTemplate (str $tpl)
Description: Outputs the entire form using a template string or file.The template delimiters { and } can be changed using setTemplateDelimiters.
Returns: True if the form was printed successfully. False if $tpl is a file that is unreadable. String when the returnOutput property is set to true. The template should use {field_name} syntax where the fields should be printed. You can pass the attr argument to printField by seperating the value with a comma (ex. {field_name,class="foobar"}).
Notes: There are several special syntax cases:
  1. An arbitrary PHP variable can be included in the template (ex. {php:varName}). A hash of up to two dimensions is also supported (ex. {php:my:foo:bar} expands to $my['foo']['bar'], {php:_SERVER:QUERY_STRING} expands to $_SERVER['QUERY_STRING']).
  2. The various breaks can be set anywhere in the template. These breaks include field, label, and option; {setBreak:field:</td><td>}, {setBreak:label:<br>}, and {setBreak:option:&nbsp;&nbsp;} respectively (see setFieldBreak, setLabelBreak, and setOptionBreak for more info.)
  3. The other two special cases are to open the form {open_form} and close the form {close_form}. You can also pass arguments to the respective methods (ex. {close_form,Do it!,onclick="validateForm();",Clear}, see openForm and closeForm.)
Multi-table Notes: Dot syntax is required: {tableName.fieldName}. This method can only be called by the root.

mixed query (str $sqlQuery [, const $resultType ])
Description: Performs an arbitrary query on the database provided in the constructor.
Returns: The raw resource as returned by mysql_query or an array if resultType is one of the constants MYSQL_ASSOC, MYSQL_NUM, or MYSQL_BOTH, as passed to mysql_fetch_array.

bool registerCallback (str $fieldName, str $functionName [, str $mode = "post" [, mixed $args = "" ]])
Description: Registers a function that is run against a field value before post or retrieval.
Parameters: fieldName is the name of the field to run the function functionName against. mode should be "post" to run the function when the form is submitted, "retrieve" when a record is retrieved for update, or "both" to run the function on both post (before insert/update) and retrieve (before display.)
Returns: True if the mode is valid and the function is callable, otherwise false.
Notes: The callback function must accept exactly three parameters: $key which is the fieldName, $value which is the value of fieldName either from the database or form submission, and $args which passes args exactly as it was passed to registerCallback (hint: pass an array or object for multiple arguments.) Return values: A value should always be returned by the callback function, that value will become the value displayed in the form and/or submitted. Using for validation: The callback can also be used as an alternate means of validation. To cause the validation to fail you must return an array with two keys, one key "status" must be set to "failed", the other key "errMsg" is the feedback message displayed to the user (ex. return array("status"=>"failed", "errMsg"=>"This field is not valid.");) Interaction with validateField: When using validateField and registerCallback on the same field the callback will only be run if the field passes normal validation first.

void registerValidation (str $methodName, str $regex [, str $errText = "Invalid input." ])
Description: Registers a new validation type.
Parameters: An arbitrary method name (later called with validateField), a PHP ereg style regular expression, and an optional string containing a default error message respectively.
Notes: Consult the PHP manual for more information: http://www.php.net/ereg/

void setBreaks (str $label, str $field [, str $option=null ])
Description: Allows you set all breaks including label, input and option in one function call. See setFieldBreak, setLabelBreak, and setOptionBreak.
Parameters: HTML code for label break, field break, and option break respectively.

void setDefaultValue (str $fieldName [, str $fieldValue="", bool $overrideRetrieved=false ])
Description: Sets the default value for a form input.
Parameters: fieldName is the name of the field to set the value for. fieldValue is the value to be set. overrideRetrieved determines whether to set the value for only a new record (false) or a retrieved value as well (true.)
Notes: For the set field type use a list of comma seperated values (ex. "value1,value2,value3".)

void setEncryptionKey (str $key)
Description: Sets a "password" for rc4 encryption/decryption of any hidden input value including the primary key and form signature. If setEncryptionKey is not called, these values are output in plain text (with exception of the form signature which isn't output at all.) It is recommended to always use encryption on any public facing form.
Parameters: A unique text string.
Notes: This function is provided as a security measure. The rc4 encryption class is provided by Mukul Sabharwal and was downloaded from mjsabby.com.
Multi-table Notes: This method can only be called by the root.

bool setFeedback (str $mode)
Description: Sets the error feedback method when input validation fails.
Parameters: Feedback method; "line" for feedback output under input labels, "box" for a feedback box above the form, or "both", default is "both".
Returns: False if the parameter is not one of the above, otherwise True.
Multi-table Notes: This method can only be called by the root.

void setFieldBreak (str $HTML)
Description: Sets the HTML output immediately following all input tags.
Parameters: HTML code, default value is "<br><br>\n\n"

void setLabelBreak (str $HTML)
Description: Sets the HTML output immediately following label tags.
Parameters: HTML code, default value is "<br>\n".
Multi-table Notes: This method can only be called by the root.

void setOptionBreak (str $HTML)
Description: Sets the HTML immediately following radio/checkbox options, useful for layout purposes.
Parameters: HTML code, default value i blank.

void setPrimaryKey (str $pkey_name)
Description: Sets the name of the table's primary key. This is necessary when 1) retrieving or updating a record using getRecord or submitForm, 2) using multiPage functionality, and 3) validating a field using uniqueField.
Parameters: Name of the table's primary key, default value is "ID".
Notes: It is recommended that you also call setEncryptionKey in scenarios 1 and 2 above. See closeForm.

void setTemplateDelimiters (str $start, str $end)
Description: Sets the start and end delimiters for the replaced tokens in a template file used with printFromTemplate.
Notes: The default values are { and } respectively.
Multi-table Notes: This method can only be called by the root.

void skipField (str $fieldName)
Description: Forces a form field to be skipped on INSERT or UPDATE, sometimes neccessary for values used in client side scripts that are not part of the table definition.
Parameters: The name of the field to skip.

bool skipFields (array $fieldNames[])
Description: Same as above but the parameter is an array of field names.
Returns: False if the argument is not an array, True otherwise.

int submitForm ([bool $echo=true ])
Description: Submits the form to the database, UPDATE the record if hidden input "pkey" is set, otherwise
INSERT a new record.
Parameters: Optionally set echo to false to return result string instead of printing it.
Returns: -1 if validation failed, 0 if query failed, 1 if query was successful, string if validation succeeded an parameter echo was false.
Multi-table Notes: This method can only be called by the root.

void toggleFieldSets (bool $toggle)
Description: Sets the fieldsets option.
Parameters: Boolean true or false, default is true.

void uniqueField (str $fieldName [, str $msg="Already taken." ])
Description: Queries existing records for the field value, validation fails if found.
Parameters: The field's name to query for, and an optional string containing a custom error message.

void validateField (str $fieldName, str $methodName [, str $errText = "NONE" ])
Description: Sets a field's validation method to validate on submit.
Parameters: The field's name, the method name (set using registerValidation), and an optional string containing a custom error message respectively. See printField notes.

Summary of Public Attributes

Set the following attributes like so: $newForm->attrName="value";

returnOutput, boolean, default value is false

Description: Set this attribute to true to return output instead of printing it. Expect a returned value from openForm, printField, closeForm, printForm, and submitForm. Useful for templating systems or any other time the output needs to be assigned to a variable.

enumField_toggle, default value of 3
setField_toggle, default value of 4
strField_toggle, default value of 70

Description: These attributes determine whether to use the default input type or the alternate based on field size. Sizes less than or equal to the default value use the alternate type. Use the forceType method to override the toggle setting.

Notes: field type to input types are as follows:
enum field default type is select, alternate is radio
set field default type is multiselect, alternate is checkbox
blob or text field default type is textarea, alternate is text

textInputLength, default value of 50
textareaRows, default value of 4
textareaCols, default value of 50
multiSelectSize, default value of 4

Description: These attributes determine input size. Visual layout should be determined by the stylesheet.

msg_insertSuccess, default value is:
<center><label class="font">Form has been submitted successfully.</label></center>
msg_insertFail, default value is:
<center><label class="font"><b>An error occurred.</b><br>Form submission failed.</label></center>
msg_updateSuccess, default value is:
<center><label class="font">Record has been updated successfully.</label></center>
msg_updateFail, default value is:
<center><label class="font"><b>An error occurred.</b><br>Record update failed.</label></center>

Description: These attributes hold the string returned on success or fail of record INSERT and UPDATE. Set them to an empty string if you want to handle success or fail manually.

err_pre, default value is <br><span class="err">
err_post, default value is </span>

err_box_pre, default value is <center><div class="errbox">
err_box_post, default value is </div></center>

Description: These attributes hold the strings output immediately before and after error messages.

mysql_errors, boolean, default value is false

Description: Set to true to output MySQL errors along with error text.