Class: Zebra_Form
source file: /Zebra_Form.php
Class Overview
Zebra_Form, a jQuery augmented PHP library for creating and validating HTML forms
Author(s):
Version:
- 2.8.2 (last revision: May 11, 2012)
Copyright:
- (c) 2006 - 2012 Stefan Gabos
Class properties
array $file_upload
An associative array of items uploaded to the current script via the HTTP POST method.
This property, available only if a file upload has occurred, will have the same values as $_FILES plus some extra values:
- path - the path where the file was uploaded to
- file_name - the name the file was uploaded with
- imageinfo - available only if the uploaded file is an image!
an array of attributes specific to the uploaded image as returned by
getimagesize() but
with meaningful names:
bits
channels
mime
width
height
type (possible types)
html
Note that the file name can be different than the original name of the uploaded file!
By design, the script will append a number to the end of a file's name if at the path where the file is uploaded to there is another file with the same name (for example, if at the path where a file named "example.txt" is uploaded to, a file with the same name exists, the file's new name will be "example1.txt").
The file names can also be random-generated. See the set_rule() method and the upload rule
Top
Class methods
constructor Zebra_Form()
void
Zebra_Form (
string
$name
,
[
string
$method
= 'POST']
,
[
string
$action
= '']
,
[
array
$attributes
= '']
)
Constructor of the class
Initializes the form.
$form =
new Zebra_Form('test-form', 'post', 'process-my-form.php', array('style' =>
'border:1px solid black'));
Parameters:
| string |
$name |
Name of the form |
| string |
$method |
(Optional) Specifies which HTTP method will be used to submit the form data set. Possible (case-insensitive) values are POST an GET Default is POST |
| string |
$action |
(Optional) An URI to where to submit the form data set. If left empty, the form will submit to itself. |
| array |
$attributes |
(Optional) An array of attributes valid for a <form> tag (i.e. style) Note that the following attributes are automatically set when the control is created and should not be altered manually: action, method, enctype, name |
Top
method add()
reference
&
add (
string
$type
,
mixed
$arguments
)
Adds a control to the form.
// create a new form
/**
* add a text control to the form
* the "&" symbol is there so that $obj will be a reference to the object in PHP 4
* for PHP 5+ there is no need for it
*/
$obj =
&$form->add('text', 'my_text');
// make the text field required
$obj->set_rule(
'required' => array(
'error', /* variable to add the error message to */
'Field is required' /* error message if value doesn't validate */
)
);
// don't forget to always call this method before rendering the form
// put code here
}
// output the form using an automatically generated template
Tags:
| return: |
Returns a reference to the newly created object |
Parameters:
| string |
$type |
Type of the control to add. Controls that can be added to a form: |
| mixed |
$arguments |
A list of arguments as required by the control that is added. |
Top
method add_error()
void
add_error (
string
$error_block
,
string
$error_message
)
Appends a message to an already existing error block
// create a new form
/**
* add a text control to the form
* the "&" symbol is there so that $obj will be a reference to the object in PHP 4
* for PHP 5+ there is no need for it
*/
$obj =
&$form->add('text', 'my_text');
// make the text field required
$obj->set_rule(
'required' => array(
'error', /* variable to add the error message to */
'Field is required' /* error message if value doesn't validate */
)
);
// don't forget to always call this method before rendering the form
/**
* for the purpose of this example, we will do a custom validation
* after calling the "validate" method.
* for custom validations, using the "custom" rule is recommended instead
*/
// check if value's is between 1 and 10
if (is_integer($_POST['my_text']) &&
$_POST['my_text']) >=
1 &&
$_POST['my_text']) <=
10) {
$form->add_error('error', 'Value must be an integer between 1 and 10!');
} else {
// put code here that is to be executed when the form values are ok
}
}
// output the form using an automatically generated template
Parameters:
| string |
$error_block |
The name of the error block to append the error message to (also the name of the PHP variable that will be available in the template file). |
| string |
$error_message |
The error message to append to the error block. |
Top
method assets_path()
void
assets_path (
string
$server_path
,
string
$url
)
Set the server path and URL to the "process.php" and "mimes.json" files.
These files are required for CAPTCHAs and uploads.
By default, the location of these files is in the same folder as Zebra_Form.php and the script will automatically try to determine both the server path and the URL to these files. However, when the script is run on a virtual host the script may not correctly determine the paths to these files. In these instances, use this method to correctly set the server path - needed by the script to correctly include these files, and the URL - needed by the client-side validation to include these files.
Also, for security reasons, I recommend moving these two files by default to the root of your website (or another publicly accessible place) and manually set the paths, in order to prevent malicious users from finding out information about your directory structure.
Parameters:
| string |
$server_path |
The server path to "process.php" and "mimes.json" files. |
| string |
$url |
The URL to "process.php" and "mimes.json" files. |
Top
method assign()
void
assign (
string
$variable_name
,
mixed
$value
)
Creates a PHP variable with the given value, available in the template file.
// create a new form
// make available the $my_value variable in the template file
$form->assign('my_value', '100');
// don't forget to always call this method before rendering the form
// put code here
}
/**
* output the form
* notice that we are using a custom template
* my_template.php file is expected to be found
* and in this file, you may now use the $my_value variable
*/
$form->render('my_template.php');
Parameters:
| string |
$variable_name |
Name by which the variable will be available in the template file. |
| mixed |
$value |
The value to be assigned to the variable. |
Top
method client_side_validation()
void
client_side_validation (
mixed
$properties
)
Sets properties for the client-side validation.
Client-side validation, when enabled, occurs on the "onsubmit" event of the form.
// create a new form
// disable client-side validation
// enable client-side validation using default properties
// enable client-side validation using customized properties
'scroll_to_error' => false, // don't scroll the browser window to the error message
'tips_position' => 'right', // position tips with error messages to the right of the controls
'close_tips' => false, // don't show a "close" button on tips with error messages
'validate_on_the_fly' => false, // don't validate controls on the fly
'validate_all' => false, // show error messages one by one upon trying to submit an invalid form
));
To access the JavaScript object and use the public methods provided by it, use $('#formname').data('Zebra_Form') where formname is the form's name with any dashes turned into underscores!
Therefore, if a form's name is "my-form", the JavaScript object would be accessed like $('my_form').data('Zebra_Form').
From JavaScript, these are the methods that can be called on this object:
- attach_tip(element, message) - displays an error message attached to the indicated jQuery element;
- hide_errors() - hides all error message tips;
- show_errors() - shows the error message/messages where required, if the form is not validated
- submit() - submits the form;
- validate() - checks if the form is valid; returns TRUE or FALSE;
Here's how you can use these methods, in a JavaScript file:
Note that this is just to show how to use each of the methods presented above, and is not the recommended way
of doing custom validations! Refer to theset_rule() method for how to do
custom validations and for a complete example on how to also use AJAX (scroll down to the "custom" rule).
// let's submit the form when clicking on a random button
// get a reference to the Zebra_Form object
var $form = $('#formname').data('Zebra_Form');
// handle the onclick event on a random button
$('#somebutton').bind('click', function(e) {
// stop default action
e.preventDefault();
// hide all error messages that might still be visible
$form.hide_errors();
// validate the form, and if the form validates
// do your own thing here
// maybe do a custom check, and attach an error message to an element
// on the form, if something is not right
if (check_something_here) $form.attach_tip($('#form_element'), 'Error!');
// if everything is ok even after the custom validation, submit the form
else $form.submit();
// if the form is not valid
// show error message/messages where required
} else $form.show_errors();
});
Parameters:
| mixed |
$properties |
Can have the following values: - FALSE, disabling the client-side validation;
- TRUE, enabling the client-side validation with the default properties;
- an associative array with customized properties for the client-side validation;
In this last case, the available properties are: - scroll_to_error, boolean, TRUE or FALSE
Specifies whether the browser window should be scrolled to the error message
or not.
Default is TRUE. - tips_position, string, left or right
Specifies where the error message tip should be positioned relative to the
control.
Default is left. - close_tips, boolean, TRUE or FALSE
Specifies whether the tips with error messages should have a "close" button
or not
Default is TRUE. - validate_on_the_fly, boolean, TRUE or FALSE
Specifies whether values should be validated as soon as the user leaves a
field; if set to TRUE and the validation of the control fails, the error
message will be shown right away
Default is FALSE. - validate_all, boolean, TRUE or FALSE
Specifies whether upon submitting the form, should all error messages be
shown at once if there are any errors
Default is FALSE.
|
Top
method doctype()
void
doctype (
[
string
$doctype
= 'html']
)
By default, this class generates HTML 4.01 Strict markup.
Use this method if you want the generated HTML markup to validate as XHTML 1.0 Strict.
Parameters:
| string |
$doctype |
(Optional) The DOCTYPE of the generated HTML markup. Possible (case-insensitive) values are HTML or XHTML Default is HTML. |
Top
method language()
void
language (
string
$language
)
Sets the language to be used by some of the form's controls (the date control, the select control, etc.)
The default language is English.
Parameters:
| string |
$language |
The name of the language file to be used, from the "languages" folder. Must be specified without extension ("german" for the german language not "german.php")! |
Top
method render()
void
render (
[
string
$template
= '']
,
[
boolean
$return
= false]
)
Renders the form.
Parameters:
| string |
$template |
The output of the form can be generated automatically, can be given from a template file or can be generated programmatically by a callback function. For the automatically generated template there are two options: - when $template is an empty string or is "*vertical", the script
will automatically generate an output where the labels are above the controls
and controls come one under another (vertical view)
- when $template is "*horizontal", the script will automatically
generate an output where the labels are positioned to the left of the controls
while the controls come one under another (horizontal view)
When templates are user-defined, $template needs to be a string representing the path/to/the/template.php. The template file itself must be a plain PHP file where all the controls added to the form (except for the hidden controls, which are handled automatically) will be available as variables with the names as described in the documentation for each of the controls. Also, error messages will be available as described at set_rule(). A special variable will also be available in the template file - a variable with the name of the form and being an associative array containing all the controls added to the form as objects. The template file must not contain the <form> and </form> tags, nor any of the
<hidden> controls added to the form as these are generated automatically! There is a third method of generating the output and that is programmatically, through a callback function. In this case $template needs to be the name of an existing function. The function will be called with two arguments: - an associative array with the form's controls' ids and their respective
generated HTML, ready for echo-ing (except for the hidden controls which will
still be handled automatically);
- an associative array with all the controls added to the form, as objects
THE USER FUNCTION MUST RETURN THE GENERATED OUTPUT! |
| boolean |
$return |
(Optional) If set to TRUE, the output will be returned instead of being printed to the screen. Default is FALSE. |
Top
method reset()
void
reset (
)
Resets the submitted values for all of the form's controls (also resets the POST/GET/FILES superglobals)
Top
method show_all_error_messages()
void
show_all_error_messages (
[
boolean
$value
= false]
)
Sets how error messages generated upon server-side validation are displayed in an error block.
Client-side validation is done on the "onsubmit" event of the form. See client_side_validation() for more information on client-side validation.
// create a new form
// display all error messages of error blocks
Parameters:
| boolean |
$value |
Setting this argument to TRUE will display all error messages of an error block, while setting it to FALSE will display one error message at a time. Default is FALSE. |
Top
method validate()
boolean
validate (
)
This method performs the server-side validation of all the form's controls, making sure that all the values comply to the rules set for these controls through the set_rule() method.
Only by calling this method will the form's controls update their values. If this method is not called, all the controls will preserve their default values after submission even if these values were altered prior to submission.
This method must be called before the render() method or error messages will not be available.
After calling this method, if there are file controls on the form, you might want to check for the existence of the $file_upload property to see the details of uploaded files and take actions accordingly.
Client-side validation is done on the "onsubmit" event of the form. See client_side_validation() for more information on client-side validation.
Tags:
| return: |
Returns TRUE if every rule was obeyed, FALSE if not. |
Top
method validate_control()
boolean
validate_control (
string
$control
)
This method performs the server-side validation of a control, making sure that the value complies to the rules set for the control through the set_rule() method.
Tags:
| return: |
Returns TRUE if every rule was obeyed, FALSE if not. |
Parameters:
| string |
$control |
Unique name that identifies the control in the form. |
Top