Formitable.class.php, 1.1 - Documentation

Description

Formitable is a PHP class used to create HTML forms from MySQL database tables. The resulting forms are completely customizable and are automatically inserted into the database on submisssion.

Summary of Public Methods

allowField
closeForm
forceType
forceTypes
getFieldLabel
getFieldValue
getLabels
getRecord
hideField
hideFields
labelField
labelFields
multiPage
normalizedField
openForm
printField
printForm
printFromTemplate *
registerCallback
registerValidation
setBreaks
setDefaultValue
setEncryptionKey
setFeedback
setFieldBreak
setLabelBreak
setOptionBreak
setPrimaryKey
setTemplateDelimiters *
skipField
skipFields
submitForm
toggleFieldSets
uniqueField
validateField
* new in ver 1.1

Legend

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

void allowField (str $fieldName)
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.
Notes: This method is only necessary when using encryption.

void closeForm ([str $submitValue="Submit", [str $attr="", [str $resetValue="Reset Form", [bool $printReset=true], [bool $closeForm=true]]]])
Description: Closes the form & prints the hidden field "pkey" if a record has been retrieved using getRecord or 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.

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", where the value is 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 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.

bool/str getFieldValue (str $fieldName)
Description: Requests a field's value, useful to test a field value before outputting it.
Parameters: The name of the field.
Returns: The field's value (when a record has been retrieved and the field is valid), otherwise False.
Notes: You must call getRecord first.

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 input values 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, False otherwise.
Notes: You must call setPrimaryKey first.

void hideField(str $fieldName)
Description: Hides a field from HTML output.
Parameters: The name of the field.

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.

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[, $action=""]]])
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. autoSubmit determines whether or not to insert/update the record automatically upon submission. action will override the default form action.

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.

bool/str printFromTemplate (str $file)
Description: Outputs the entire form using a template file.
Returns: True if file is a valid file and the form was printed successfully, False if file doesn't exist or 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. The first allows an arbitrary php variable to 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']). The second special case allows the various breaks to 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.) The other two special cases are to open the form {open_form} and close the form {close_form}, where you can also pass arguments to the respective functions (ex. {close_form,Do it!,onclick="validateForm();",Clear}, see closeForm.) The template delimiters { and } can be changed using setTemplateDelimiters.

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.) A value should always be returned by the callback function, that value will become the value submitted and/or displayed in the form. 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.");)

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="NONE"])
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.

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.

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".

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.

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.

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>"

Description: These attributes hold the strings outputted 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.

jsLabels, default value is false

Description: Mozilla based browsers among others allow the user to click labels in order to select or otherwise focus input fields. This attribute determines whether or not to output a javascript onClick attribute to mimic this useful functionality in browsers that lack it (IE5.5 and lower.)

Notes: This property is deprecated and will likely be removed in a future release.