Package: Zebra_Form

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.

  1. $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.

  1.  //  create a new form
  2.  $form new Zebra_Form('my_form');
  3.  
  4.  /**
  5.   *  add a text control to the form
  6.   *  the "&" symbol is there so that $obj will be a reference to the object in PHP 4
  7.   *  for PHP 5+ there is no need for it
  8.   */
  9.  $obj &$form->add('text''my_text');
  10.  
  11.  // make the text field required
  12.  $obj->set_rule(
  13.       'required' => array(
  14.          'error',            /* variable to add the error message to */
  15.          'Field is required' /* error message if value doesn't validate */
  16.       )
  17.  );
  18.  
  19.  // don't forget to always call this method before rendering the form
  20.  if ($form->validate()) {
  21.      // put code here
  22.  }
  23.  
  24.  //  output the form using an automatically generated template
  25.  $form->render();
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

  1.  //  create a new form
  2.  $form new Zebra_Form('my_form');
  3.  
  4.  /**
  5.   *  add a text control to the form
  6.   *  the "&" symbol is there so that $obj will be a reference to the object in PHP 4
  7.   *  for PHP 5+ there is no need for it
  8.   */
  9.  $obj &$form->add('text''my_text');
  10.  
  11.  // make the text field required
  12.  $obj->set_rule(
  13.       'required' => array(
  14.          'error',            /* variable to add the error message to */
  15.          'Field is required' /* error message if value doesn't validate */
  16.       )
  17.  );
  18.  
  19.  // don't forget to always call this method before rendering the form
  20.  if ($form->validate()) {
  21.  
  22.      /**
  23.       *  for the purpose of this example, we will do a custom validation
  24.       *  after calling the "validate" method.
  25.       *  for custom validations, using the "custom" rule is recommended instead
  26.      */
  27.  
  28.      // check if value's is between 1 and 10
  29.      if (is_integer($_POST['my_text']&& $_POST['my_text']>= && $_POST['my_text']<= 10{
  30.  
  31.          $form->add_error('error''Value must be an integer between 1 and 10!');
  32.  
  33.      else {
  34.  
  35.          // put code here that is to be executed when the form values are ok
  36.  
  37.      }
  38.  
  39.  }
  40.  
  41.  //  output the form using an automatically generated template
  42.  $form->render();
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.

  1.  //  create a new form
  2.  $form new Zebra_Form('my_form');
  3.  
  4.  // make available the $my_value variable in the template file
  5.  $form->assign('my_value''100');
  6.  
  7.  // don't forget to always call this method before rendering the form
  8.  if ($form->validate()) {
  9.      // put code here
  10.  }
  11.  
  12.  /**
  13.   *  output the form
  14.   *  notice that we are using a custom template
  15.   *  my_template.php file is expected to be found
  16.   *  and in this file, you may now use the $my_value variable
  17.   */
  18.  $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.

  1.  //  create a new form
  2.  $form new Zebra_Form('my_form');
  3.  
  4.  // disable client-side validation
  5.  $form->client_side_validation(false);
  6.  
  7.  // enable client-side validation using default properties
  8.  $form->client_side_validation(true);
  9.  
  10.  // enable client-side validation using customized properties
  11.  $form->client_side_validation(array(
  12.      'scroll_to_error'       =>  false,      //  don't scroll the browser window to the error message
  13.      'tips_position'         =>  'right',    //  position tips with error messages to the right of the controls
  14.      'close_tips'            =>  false,      //  don't show a "close" button on tips with error messages
  15.      'validate_on_the_fly'   =>  false,      //  don't validate controls on the fly
  16.      'validate_all'          =>  false,      //  show error messages one by one upon trying to submit an invalid form
  17.  ));

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

  1.  //  let's submit the form when clicking on a random button
  2.  
  3.  // get a reference to the Zebra_Form object
  4.  var $form = $('#formname').data('Zebra_Form');
  5.  
  6.  // handle the onclick event on a random button
  7.  $('#somebutton').bind('click'function(e{
  8.  
  9.      // stop default action
  10.      e.preventDefault();
  11.  
  12.      // hide all error messages that might still be visible
  13.      $form.hide_errors();
  14.  
  15.      // validate the form, and if the form validates
  16.      if ($form.validate()) {
  17.  
  18.          // do your own thing here
  19.  
  20.          // maybe do a custom check, and attach an error message to an element
  21.          // on the form, if something is not right
  22.          if (check_something_here$form.attach_tip($('#form_element')'Error!');
  23.  
  24.          // if everything is ok even after the custom validation, submit the form
  25.          else $form.submit();
  26.  
  27.      // if the form is not valid
  28.      // show error message/messages where required
  29.      else $form.show_errors();
  30.  
  31.  });
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.

  1.  //  create a new form
  2.  $form new Zebra_Form('my_form');
  3.  
  4.  //  display all error messages of error blocks
  5.  $form->show_all_error_messages(true);
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