Form Helper Class
The idea of this class is to eliminate a lot of the repetitious code that we always end up writing when constructing forms without having to load up an entire bulky framework. I started developing this back in May 2011 and am still working on it, so it will probably change some in the future, but I've already implemented in several places so I'll always try to keep new versions backwards compatible. If you come across any bugs or have suggestions, please leave them in the comments area.
To start, view and then download form.class.php. I've included a fair number of comments in there, so you can hopefully follow along easily. Then, you can read the documentation on the functions that I've included on this page. And, finally, you can check out this example (and view the code for it). Alternately, you can start with this blank form code.
start() · end() · process() · text() · radios() · checkboxes() · dropdown() · textarea() · date() · file() · hidden() · submit()$form->start()
Starts the form and generates the opening <form> tag. Required.
Required Variables: None
Optional Variables:
- action – Where to submit the form, defaults to $_SERVER['PHP_SELF']
- method – Form Method (get or post), defaults to post
- name – Form Name
- id – Form ID
- extra – An extra string to be included within the <form> tag such as JavaScript or styling.
- hidden – Array of hidden inputs that you'd like included. They can be passed as strings or arrays.
- multipart – Sets the forms enctype. Needs to be set to TRUE if you're including file uploads. Defaults to FALSE.
$form->end()
Closes the form and generates the </form> tag. Required (because it includes hidden fields needed for form processing).
Required Variables: None
Optional Variables: None
$form->process()
Processes the submitted form and returns an array of data on success.
Required Variables: None
Optional Variables:
- cleanup_function – The default cleanup function to use on submitted data. See standard_cleanup() below the class for a good example. This can be overwritten by the individual form fields' settings.
- error_function – A function to error check all the data together. Expects the $data array to be the one and only argument. Should return TRUE on success, FALSE on failure. Any errors generated should be stored in $GLOBALS['error'] as either a string or an array – they will be transfered from there to $form->error_message.
- fields – An array of the fields to be process. Required if sessions are not enabled. Can be easily generated using the $form->fields() function.
- force – Whether or not to force processing of the form. This is useful if you pass variables through the URI query string and want them to be processed. Defaults to FALSE.
- form_name – The name of the form to process. This should be figured out automatically because of a submitted hidden field generated in $form->end().
- combine_multiples – If set, fields that normally return an array will be imploded with this string (a comma is a good one to use).
- all_errors_at_top – If set to TRUE, all of the errors will be displayed in $form->error_message instead of being attached to the relevant fields throughout the form.
$form->text()
Generates a text or password input field.
Required Variables:
- name – The name of the form element.
Optional Variables:
- value – The value that should be displayed on first form load. (Won't show up on password fields.)
- id – The ID of the form element.
- password – If set to TRUE, changes the element type to a password field.
- size – Sets the size attribute.
- maxchars – The maximum number of characters allowed.
- extra – An extra string to be included within the tag such as JavaScript or styling.
- disabled – If set to TRUE, disables the element.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->radios()
Generates a set of radio fields.
Required Variables:
- name – The name of the form element.
- options – An array with all the possible answers (when the form is processed, the array keys are passed as values). Note: If you set $GLOBALS['name_options'] as an array, it will be used instead. This is helpful for database driven lists that update frequently.
Optional Variables:
- value – The key of the element that should be checked on the first form load.
- return_array – If set to TRUE, returns the radios code as an array instead of a string. Note that this causes inline errors not to be displayed.
- separator – What to separate the radios with. For example, a space or line break.
- extra – An extra string to be included within each radio input tag such as JavaScript or styling.
- disabled – If set to TRUE, disables the element.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->checkboxes()
Generates a set of check boxes. Generates an array upon form submit unless combine_multiples is set in $form->process().
Required Variables:
- name – The name of the form element.
- options – An array with all the possible answers (when the form is processed, the array keys are passed as values). Note: If you set $GLOBALS['name_options'] as an array, it will be used instead. This is helpful for database driven lists that update frequently.
Optional Variables:
- value – The key(s) of the element(s) that should be checked on the first form load. Can be either a string or an array.
- return_array – If set to TRUE, returns the checkboxes input code as an array instead of a string. Note that this causes inline errors not to be displayed.
- separator – What to separate the checkboxes with. For example, a space or line break.
- extra – An extra string to be included within each checkbox input tag such as JavaScript or styling.
- disabled – If set to TRUE, disables the element.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->dropdown()
Generates a dropdown select element or a multiple select element.
Required Variables:
- name – The name of the form element.
- options – An array with all the possible answers (when the form is processed, the array keys are passed as values). You can include an array with group (true), caption, and options set in order to have an option group included. Note: If you set $GLOBALS['name_options'] as an array, it will be used instead. This is helpful for database driven lists that update frequently.
Optional Variables:
- value – The key(s) of the element(s) that should be selected on the first form load. Can be either a string or an array if multiple is set to TRUE.
- id – The ID of the form element.
- multiple – If set to TRUE, allows the user to select more than one option. Generates an array upon form submit unless combine_multiples is set in $form->process(). If set, size should be made greater than 1.
- size – Number of rows to show. Defaults to 1
- force_size – If set to TRUE, this keeps the size from shrinking to the number of options passed.
- blank – If set to TRUE, includes a blank option with a null value. If set to a string, it includes an option with that string as a caption and a null value. If set to FALSE, no null value will be included in the dropdown.
- extra – An extra string to be included within the tag such as JavaScript or styling.
- disabled – If set to TRUE, disables the element.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->textarea()
Generates a textarea field.
Required Variables:
- name – The name of the form element.
Optional Variables:
- value – The value that should be displayed on first form load.
- id – The ID of the form element.
- rows – The number or rows tall the field should be.
- cols – The number or columns wide the field should be.
- extra – An extra string to be included within the tag such as JavaScript or styling.
- disabled – If set to TRUE, disables the element.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->date()
Generates a set of dropdown select elements (and optionally a text field for the time) for the user to enter a date. Submitted value is translated into a UNIX timestamp.
Required Variables:
- name – The name of the field. Note: the indiviual elements will have different names, but the data will be stored as whatever the main name is set to.
Optional Variables:
- value – The UNIX timestamp of the date & time that should be selected on the first form load.
- blank – If set to TRUE, includes a blank option with a null value at the top of each dropdown. If set to a string, it includes an option with that string as a caption and a null value. If set to FALSE, no null value will be included in the dropdown.
- time_box – If set to TRUE, a text field for the time to be entered as a string (to be processed by strtotime) will be added at the end.
- time_blank – If set to TRUE, the time box will appear without a value, even if a value for the date is provided.
- first_year – The first year to display in the years dropdowns. Defaults to 1970.
- last_year – The first year to display in the years dropdowns. Defaults to 2030.
- reverse_year_order – If set to TRUE, returns the years sorted in descending order.
- return_array – If set to TRUE, returns the code in as an array instead of a string separated by spaces.
- allow_year_only – If set to TRUE, the form allows just a year to be set. In that case, a submitted value will be returned as a year, not a timestamp.
- extra – An extra string to be included within the each select and input tag such as JavaScript or styling.
- disabled – If set to TRUE, disables all the associated elements.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->file()
Generates a file upload field. If used, multipart needs to be set to TRUE in $form->start().
Required Variables:
- name – The name of the form element.
Optional Variables:
- allowed_file_types – An array of the allowed upload extensions. Case insensitive.
- id – The ID of the form element.
- upload_directory – The directory where uploaded files should be stored. Needs to be writeable. Overwrites the default upload_directory that can be set when $form is constructed.
- required_width – If set, the uploaded file must be a recognized image type and this width (in pixels) or an error will be thrown.
- required_height – If set, the uploaded file must be a recognized image type and this height (in pixels) or an error will be thrown.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->hidden()
Generates a hidden input field. Normally, you would just include these in $form-start(), but this is available in case you need it.
Required Variables:
- name – The name of the hidden element.
Optional Variables:
- value – The value of the hidden element to be submitted.
- id – The ID of the hidden element.
- required – If set to TRUE, throws an error when a value is not submitted.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
$form->submit()
Generates a submit button.
Required Variables: None
Optional Variables:
- value – The value & caption of the button.
- caption – The value & caption of the button. Gets overwritten by value if it is set.
- name – The name of the form element.
- id – The ID of the form element.
- extra – An extra string to be included within the tag such as JavaScript or styling.
- required – If set to TRUE, throws an error when a value is not submitted.
- disabled – If set to TRUE, disables the element.
- cleanup_function – A function to clean the data submitted by the user for this specific element. Overwrites the cleanup_function set in $form->process if set.
- error_function – A function to error check the data submitted by the user for this specific element. Should return TRUE if okay, FALSE if it failed. Errors should be sent to $GLOBALS['error'] as either a string or an array. If set, this check is performed in addition to the error_function set in $form->process().
Example Code
If you're like me, examples help a lot. So, I've constructed this basic example form, the code for which is displayed here:
<?php
$pagetitle = 'Example Ink Plant Form Helper Generated Form';
require 'header.inc';
echo "<h1>$pagetitle</h1>";
$GLOBALS['animals_options'] = array('b'=>'Bear','t'=>'Tiger','l'=>'Lion');
$GLOBALS['plants_options'] = array(
'j'=>'Juniper Bush'
,'g'=>'Grass'
,'f'=>array('group'=>true,'caption'=>'Flowers','options'=>array('o'=>'Orchid','s'=>'Sunflower','r'=>'Rose'))
,'t'=>array('group'=>true,'caption'=>'Trees','options'=>array('p'=>'Palm Tree','pi'=>'Pine Tree'))
);
require_once DATA_DIR.'form.class.php';
$form = new Form(array('use_sessions'=>true));
$data = $form->process(array('form_name'=>'test','combine_multiples'=>', ','cleanup_function'=>'standard_cleanup'));
if ($form->success) {
echo "<p>Form successfully submitted.</p>";
echo "<ul>";
foreach ($data as $key => $value) {
echo "<li>$key = ".htmlspecialchars($value)."</li>";
}
echo "</ul>";
} else {
echo $form->error_message;
$hidden = array('testing'=>'yes','apple'=>'green');
echo $form->start(array('name'=>'test','hidden'=>$hidden));
echo "<table>";
echo "<tr><th>Required Text</th><td>".$form->text(array('name'=>'field1','caption'=>'Field One','required'=>true))."</td></tr>";
echo "<tr><th>Optional Text</th><td>".$form->text(array('name'=>'field2','caption'=>'Field Two','value'=>'something','required'=>false))."</td></tr>";
$options = array('b'=>'Blue','g'=>'Green','y'=>'Yellow');
echo "<tr><th>Radios</th><td>".$form->radios(array('name'=>'radio1','options'=>$options,'value'=>'b','required'=>true))."</td></tr>";
echo "<tr><th>Radios Again</th><td>".$form->radios(array('name'=>'animals','value'=>'b','required'=>true))."</td></tr>";
echo "<tr><th>Checkboxes</th><td>".$form->checkboxes(array('name'=>'check','caption'=>'Color Checks','options'=>$options,'value'=>array('b','y'),'required'=>true))."</td></tr>";
echo "<tr><th>Dropdown</th><td>".$form->dropdown(array('name'=>'dd_single','options'=>$options,'blank'=>true))."</td></tr>";
echo "<tr><th>Grouped Dropdown</th><td>".$form->dropdown(array('name'=>'plants','blank'=>true))."</td></tr>";
echo "<tr><th>Dropdown Multiple</th><td>".$form->dropdown(array('name'=>'dd_multi','multiple'=>true,'size'=>3,'options'=>$options))."</td></tr>";
echo "<tr><th>Date</th><td>".$form->date(array('name'=>'time'))."</td></tr>";
echo "<tr><th> </th><td>".$form->submit(array('caption'=>'Submit Test'))."</td></tr>";
echo "</table>";
echo "<p>Here are the fields that are being used:</p>";
echo $form->fields(array('form_name'=>'test','return_php'=>true));
echo $form->end();
}
echo "<hr /><p>This page is an example for the article <a href=\"http://www.inkplant.com/code/form-helper.php\">Form Helper Class</a>. You can view the PHP code for it on that page.</p>" ;
require 'footer.inc';
?>If you have questions (or suggestions), please leave them in the comments below.
This post was published on Friday, July 8th, 2011 by Robert James Reese in the following categories: HTML, PHP. Before using any of the code or other content in this post, you must read and agree to our Terms & Conditions.
0 Comments
Be the first to leave a comment.
Leave a Comment