PhpToolCase
[ class tree: PhpToolCase ] [ index: PhpToolCase ] [ all elements ]
Prev Next

PtcForms User Guide

Html Dynamic Forms Generator/Validator - VERSION 0.8.1

Table of Contents

INTRODUCTION

The dynamic html forms generator is an excellent tool that will help you build all kinds of html forms in just a few minutes. It will make you forget about all the problems involved with fields alignment, layouts, and server-side validation. For client-side validation the wonderfull jquery validator plugin can be used. This class is especially adviced to webdesigners and webmasters that are having troubles with html forms.

Main Features:

  • Fast and easy to use, for building and validating html forms
  • Completely flexible, can adapt to any web environment
  • Built in validator which supports custom methods
  • Automatic labels and fields alignment
  • Html templates can be all manipulated
  • No additional css files are needed for the class to work
  • Uses PtcDebug class to debug the building process

GETTING STARTED

Add the following lines to load the class:

  1. # initialize the class
  2.     require_once('PtcForms.php');
  3.     $ptc=new PtcForms();

CLASS OPTIONS

This is the full list of options available on intialization, stored in $_defaultOptions property:

  1. $options=array
  2.     (
  3.         "form_method"            =>    "post",    # the form method to use
  4.         "form_action"            =>    "#",        # the form action url
  5.         "form_width"            =>    "500px",    # the width for the main container
  6.         "add_class_validator"    =>    false,    # add validator classes to fields for use with jquery
  7.         "labels_align"            =>    "left",    # align labels globally(left,top,right)
  8.         "labels_width"            =>    "40%",    # the width for labels as a percentage
  9.         "style_elements"        =>    true,    # add default style to input elements to align properly
  10.         "style_labels"            =>    true,    # add default style to label elements to align properly
  11.         "style_tables"            =>    true,    # add default style to table elements to align properly
  12.         "spacer_height"        =>    "3px",    # height for the spacer between fields
  13.         "keep_values"            =>    true,    # repopulate filled fields on form submission
  14.         "print_form"            =>    true,    # print form to screen or return html only
  15.         "start_tab"            =>    "\t",        # format html code with tabs
  16.         "err_msg_level"        =>    E_USER_WARNING,# error messages level
  17.     );
  18.     
  19.     # initialize the class
  20.     require_once('PtcForms.php');
  21.     $ptc=new PtcForms($options);

form_method

Use this option to set form method(post/get).

Default value: post (string)


form_action

This option can be used to set form action attribute. Ex: process-form.php

Default value: # (string)


form_width

Use this option to set the width of the form.

Default value: 500px (string)


add_class_validator

This option adds the respective css classes to fields to validate client side with jquery and the ptcforms-validator.js plugin. See ADDING AND VALIDATING FIELDS WITH THE VALIDATOR ENGINE for details and usage.

Default value: false (bool)


labels_align

This option can be used for the form layout, it will attempt to align the labels with the fields. Options are "left","right","top" or "none" for no labels.

Default value: left (string)


labels_width

Use "labels_width" to set the width for the labels. Always make sure that the form has the currect width, otherwise the result will not be as expected. You can refer to getting_started.form_width for the form width option.

Default value: 40% (string)


style_elements

This option can be used to stop adding styles to the input fields automatically, quite usefull if you want to use your own css. The default styles for the inputs are stored in the $_inputStyles property, and can be manipulated with the setInputStyle() method. see Changing default styles for fields for a detailed usage.

Default value: true (bool)

  1. # Default input styles
  2.     $_inputStyles=array
  3.     (
  4.         "radio"    =>    array("padding"=>"0px","margin"=>"0px","vertical-align"=>"middle","width"=>"14px"),
  5.         "input"    =>    array("margin"=>"0px","padding"=>"3px","border"=>"1px inset"),
  6.         "button"    =>    array("margin"=>"0px")
  7.     );


style_labels

This option can be used to stop adding styles to the label containers automatically, quite usefull if you want to use your own css. The default styles for the labels are stored in the $_labelStyles property, and can be manipulated with the setLabelStyle() method. see Changing default styles for label containers for a detailed usage.

Default value: true (bool)

  1. # Default label container styles
  2.     $_labelStyles=array
  3.     (
  4.         # Styles for input, select and textarea
  5.         1    =>    array("left"=>array("float"=>"left","margin"=>"2px 0 0 0","width"=>"{label_width}%"),//margin:1px 0 0 0
  6.                     "right"=>array("float"=>"left","margin"=>"1px 3px 0 0",//margin:0 3px 0 0;
  7.                                     "text-align"=>"right","width"=>"{label_width}%"),
  8.                     "top"=>array()),
  9.         # Styles for checkbox and radio buttons
  10.         2    =>    array("left"=>array("vertical-align"=>"middle","border"=>"none"),
  11.                     "right"=>array("vertical-align"=>"middle","border"=>"none"),
  12.                     "top"=>array()),
  13.         # Styles for radio/checkbox group and composite fields
  14.         3    =>    array("left"=>array("float"=>"left","margin"=>"3px 0 0 0","width"=>"{label_width}%"),
  15.                     "right"=>array("float"=>"left","margin"=>"1px 3px 0 0",
  16.                                     "text-align"=>"right","width"=>"{label_width}%"),
  17.                     "top"=>array())
  18.     );


style_tables

This option can be used to stop adding width to the tables automatically, quite usefull if you want to use your own css.

Default value: true (bool)


spacer_height

The "spacer_height" option property can be used to change the height between fields.

Default value: 3px (bool)


keep_values

This options is used to load already inserted values in the fields if form was submitted. It could be usefull set to false, for a login form as inserted values will not be reproposed upon submission, as shown in the pctforms-ex1.php example file

Default value: true (bool)


print_form

Prints the form or returns the output generated by the {@render()} method as a string if set to false.

Default value: true (bool)


start_tab

This option controls the start tab for the html output. If the you would like to increase the offset add more tabs, ex: \t\t\t

Default value: \t (string)


err_msg_level

The "err_msg_level" is used to set the severity of the error for execution errors within the class itself. Use E_USER_NOTICE for a lower severity and E_USER_ERROR for a higher severity

Default value: E_USER_WARNING (const)


ADDING FIELDS

The addField() method is used to add form fields. Works with all input types, but some extra paramaters can be passed aswell to create custom html. Parameters used are the type and a unique name for the field.

Possible field types:

  1. text
  2. password
  3. radio
  4. checkbox
  5. checkboxgroup
  6. radiogroup
  7. select
  8. fieldset
  9. composite (for complex field layouts)
  10. custom (any html code can be passed as value)
  11. submit
If a different "type" is used, the class will attempt to load the default options of the "text" input.

The following sections will try to demonstrate how we can add some of these fields:

Adding a Text Field

This is how we can add a text field.

  1. # adding a text field
  2.     $ptc->addField("text","fieldName");        
  3.     # adding a label to the text field    
  4.     $ptc->addFieldLabel("fieldName","labelText");        
  5.     # adding a value that will be shown inside the input
  6.     $ptc->addFieldValue("fieldName","some text");
The following fields can be added like shown in the example above: text, textarea, password, radio, checkbox, submit, custom (any html code can be passed as value).


Adding a Select Field

This is how wed can add a select field, to make an option selected you can use the "=>" operator.

  1. # adding a select field
  2.     $ptc->addField("select","fieldName1");    
  3.     # adding a label to the select field    
  4.     $ptc->addFieldLabel("fieldName1","labelText1");        
  5.     # array of values for the select, radiogroup and checkboxgroup work just the same
  6.     $select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");    
  7.     # adding the values to the select field
  8.     $ptc->addFieldValues("fieldName1",$select_values);    
  9.     # setting attribute checked on 1 select option
  10.     # works for all fields inside 1 level above like 
  11.     # composites,radio/checkbox groups fieldsets and selects
  12.     $ptc->addFieldAttributes("fieldName1=>maybe",array("selected"=>true));
The following fields can be added like shown in the example above: select, radiogroup, checkboxgroup.


Adding a Checkboxgroup

This is how wed can add a checkboxgroup, to make a checkbox checked you can use the "=>" operator. Also, the "cols" attribute controls how many columns the group will have. The default value is 1.

  1. # adding a checkboxgroup
  2.     $ptc->addField("checkboxgroup","fieldName2[]");    
  3.     # adding a label to the checkboxgroup
  4.     $ptc->addFieldLabel("fieldName2[]","labelText2");        
  5.     # array of values for checkboxgroup field, radiogroup and select work just the same
  6.     $select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");    
  7.     # adding the values to the checkboxgroup
  8.     $ptc->addFieldValues("fieldName2[]",$select_values);
  9.     # setting the labels to apper at the right of the boxes, default form alignment is left
  10.     # addvaluesparams() is used to add paramters to all values of 1 field at once, like radio/checkbox groups
  11.     $ptc->addValuesParams("fieldName2[]","labelOptions",array("align"=>"right"));
  12.     # setting 2 columns for 3 values previously added, default for radio/checkbox group is 1    
  13.     $ptc->addFieldAttributes("fieldName2[]",array("cols"=>2));
  14.     # setting attribute checked on 1 checkbox
  15.     $ptc->addFieldAttributes("fieldName2[]=>yes",array("checked"=>true));
The following fields can be added like shown in the example above: select, radiogroup, checkboxgroup.


Adding a Composite

Composite fields are used for complex layouts, as the can be nested inside each other. This allows to have many fields inline for example or a form with fields in 2 columns. The "cols" attribute controls how many columns the composite field will have. The default value is inline.

  1. # adding a composite 
  2.     $ptc->addField("composite","fieldName3");            
  3.     # adding the previously created text and select fields to to the composite
  4.     $ptc->addFieldValue("fieldName3",array("fieldName","fieldName1"));
  5.     # setting the composite for 1 column only, default is all fields inline
  6.     $ptc->addFieldAttributes("fieldName3",array("cols"=>1));
The following fields can be added like shown in the example above: fieldset, composite.


Adding a Fieldset

Fieldsets are used for previously created fields, that can be added as values. The label will act as legend.

  1. # adding a fieldset
  2.     $ptc->addField("fieldset","fieldName4");    
  3.     # adding some text to the the fieldset legend    
  4.     $ptc->addFieldLabel("fieldName4","Some text");    
  5.     # adding the previously created composite and checkboxgroup fields to to the fieldset
  6.     $fieldset_values=array("fieldName3","fieldName2[]");        
  7.     # adding previously created fields as values to the fieldset    
  8.     $ptc->addFieldValues("fieldName4",$fieldset_values);
The following fields can be added like shown in the example above: fieldset, composite.


Adding a Custom Field for a Spacer

This is how we can add a custom field, in this case we will use the addSpacer() method, but keep in mind that any html can be passed as value to this field type.

  1. # creating a custom field for a space
  2.     $ptc->addField("custom","spacer1");
  3.     # adding the a spacer to the custom field, any html can be passed as value
  4.     # for custom type only addfield() and addfieldvalue() are allowed
  5.     $ptc->addFieldValue("spacer1",$ptc->addSpacer("3px"));


ADDING LABELS

The addFieldLabel() method adds a label to the field specified by the $fieldName param.

We can add a label to a field like this:

  1. # adding a text field
  2.     $ptc->addField("text","fieldName");        
  3.     # adding a label to the text field    
  4.     $ptc->addFieldLabel("fieldName","labelText");        
  5.     # adding a value that will be shown inside the input
  6.     $ptc->addFieldValue("fieldName","some text");
We can add a label to the fieldset aswell:
  1. # adding a fieldset
  2.     $ptc->addField("fieldset","fieldName4");    
  3.     # adding some text to the the fieldset legend    
  4.     $ptc->addFieldLabel("fieldName4","Some text");    
  5.     # adding the previously created composite and checkboxgroup fields to to the fieldset
  6.     $fieldset_values=array("fieldName3","fieldName2[]");        
  7.     # adding previously created fields as values to the fieldset    
  8.     $ptc->addFieldValues("fieldName4",$fieldset_values);

ADDING VALUES TO FIELDS

The addFieldValues() and addFieldValue() methods are used to add values to form fields. An array is passed as the $options parameter for select,checkboxgroup,radiogroup,fieldset and composite fields. The rest of the fields use a string as value for the $options parameter.

Adding values as a string

the following fields accept a value as a string:

  1. text
  2. textarea
  3. password
  4. radio
  5. checkbox
  6. custom (any html code can be passed as value)
  7. submit
This is how we can add a value to a field as a string:
  1. $ptc->addFieldValue("fieldName","some text");


Adding values as an array

the following fields accept an array as a field value:

  1. select
  2. radiogroup
  3. checkboxgroup
The following examples demostrate how we can add an array as a field value:
  1. # adding a select field
  2.     $ptc->addField("select","fieldName1");    
  3.     # adding a label to the select field    
  4.     $ptc->addFieldLabel("fieldName1","labelText1");        
  5.     # array of values for the select, radiogroup and checkboxgroup work just the same
  6.     $select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");    
  7.     # adding the values to the select field
  8.     $ptc->addFieldValues("fieldName1",$select_values);
  1. # adding a checkboxgroup
  2.     $ptc->addField("checkboxgroup","fieldName2[]");    
  3.     # adding a label to the checkboxgroup
  4.     $ptc->addFieldLabel("fieldName2[]","labelText2");        
  5.     # array of values for checkboxgroup field, radiogroup and select work just the same
  6.     $select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");    
  7.     # adding the values to the checkboxgroup
  8.     $ptc->addFieldValues("fieldName2[]",$select_values);


Adding fields as array of values(composite,fieldset)

the following fields accept an array with previously created field names as values:

  1. fieldset
  2. composite
The following examples demostrate how we can add previously created fields as an array of values:
  1. # adding a composite 
  2.     $ptc->addField("composite","fieldName3");            
  3.     # adding the previously created text and select fields to to the composite
  4.     $ptc->addFieldValue("fieldName3",array("fieldName","fieldName1"));
  5.     # setting the composite for 1 column only, default is all fields inline
  6.     $ptc->addFieldAttributes("fieldName3",array("cols"=>1));
  7.     
  8.     
  9.     # adding a fieldset
  10.     $ptc->addField("fieldset","fieldName4");    
  11.     # adding some text to the the fieldset legend    
  12.     $ptc->addFieldLabel("fieldName4","Some text");    
  13.     # adding the previously created composite and checkboxgroup fields to to the fieldset
  14.     $fieldset_values=array("fieldName3","fieldName2[]");        
  15.     # adding previously created fields as values to the fieldset    
  16.     $ptc->addFieldValues("fieldName4",$fieldset_values);
Composite fields can be nested to achieve complex layouts, but rememeber to always add the fields in the proper order or the class will not find them. When using composite, you can use the "=>" operator to add options to the composite values, see Adding attributes to fields.


ADDING PARAMETERS TO VALUES

The addValuesParams() method is used to add a certain paramater to multiple values at once like checkbox/radio groups. Have a look at the following example to see it in action:

  1. # adding a checkboxgroup
  2.     $ptc->addField("checkboxgroup","fieldName2[]");    
  3.     # array of values for checkboxgroup field, radiogroup and select work just the same
  4.     $select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");    
  5.     # adding the values to the checkboxgroup
  6.     $ptc->addFieldValues("fieldName2[]",$select_values);
  7.     # addvaluesparams() is used to add paramters to all values of 1 field at once, like radio/checkbox groups
  8.     # adding onmouseover to all values of checkboxgroup in 1 line
  9.     $ptc->addValuesParams("fieldName2[]","events",array("onmouseover"=>"alert(\'some text\')"));
  10.     # setting the labels to apper at the right of the boxes, default form alignment is left
  11.     $ptc->addValuesParams("fieldName2[]","labelOptions",array("align"=>"right"));
Possible options for the "$type" parameter are stored in the _storageKeys property:
  1. # possible storage keys for addValuesParams()
  2.     $_storageKeys=array("events","attributes","validate","label","labelOptions","parentEl");
.

ADDING HTML ATTRIBUTES TO ELEMENTS

This section will try to cover how to add attributes to fields, labels and containers. All Attributes are stored in _elAttributes property. New attributes can be added with the addElAttribute() and addElAttributes() methods, see Extending the compiler with custom attributes.

  1. # these are the default elements attributes, more can be added with the addElAttributes() method
  2.     $_elAttributes=array('class','id','style','value','maxlength','size','disabled','checked','target','events',
  3.                         'title','selected','cols','rows','equalTo','border','pattern','cellpadding','cellspacing');

Adding attributes to fields

The addFieldAttributes() method is used to add html attributes to form fields.

  1. # adding a textarea field
  2.     $ptc->addField("textarea","textAreaField");
  3.     # adding html attributes to the textarea, set style=>false to remove default styles for 1 field
  4.     $ptc->addFieldAttributes("textAreaField",array("id"=>"fieldID","class"=>"some-class","style"=>false));
To add an attribute to a select option, or a checkbox/radio inside a group we can use the following operator "=>" in the fieldname parameter, as shown in the next example:
  1. # setting attribute checked on 1 checkbox
  2.     $ptc->addFieldAttributes("fieldName2[]=>yes",array("checked"=>true));


Adding attributes to label container

The addLabelOptions() method is used to add html attributes to the label container.

  1. # setting a different style and changing alignment for a label container
  2.     $ptc->labelOptions("someFieldName"=>array("align"=>"top","style"=>"margin:10px"));
  3.     # setting an id and a class for the label container, and adding style=>false to remove the default label container style
  4.     $ptc->labelOptions("someFieldName"=>array("id"=>"someID","class"=>"some-class","style"=>false));


Adding attributes to field container

The fieldParentEl() method is used to add html attributes to the field container.

  1. # adding a submit button
  2.     $ptc->addField("submit","submitButton");
  1. # adding html attributes to the parent div of a submit button, 
  2.     # set "style"=>false to remove default styles for 1 field
  3.     $ptc->fieldParentEl("submitButton",array("style"=>"text-align:right;"));


Extending the compiler with custom attributes

The addElAttribute() and addElAttributes() methods are used to add more attributes to be compiled with the fields and containers. The default attributes are stored in the _elAttributes property:

  1. # adding an attribute to the the _elAttributes property
  2.     $ptc->AddElAttributes("default-value");
  3.     # adding an array of attributes
  4.     $ptc->AddElAttributes(array("default-value","tabindex"));


CHANGING DEFAULT STYLES APPLIED TO ELEMENTS

The methods setInputStyle() and setLabelStyle() can be used to manipulate the default styles for fields and label containers. The following chapters will try to cover these methods with practical examples.

Changing default styles for fields

The setInputStyle() method is used to change the default styles for the fields.

  1. # changing the default styles for radio/checkbox fields, removing "vertical-align" property
  2.     $ptc->setInputStyle(array("margin"=>"0 10px 0 0","vertical-align"=>false),"radio");
  3.     # changing the default styles for input fields
  4.     $ptc->setInputStyle(array("padding"=>"3px","border"=>"none"),"input");
The dafault styles are stored in the $_inputStyles property.
  1. # Default input styles
  2.     $_inputStyles=array
  3.     (
  4.         "radio"    =>    array("padding"=>"0px","margin"=>"0px","vertical-align"=>"middle","width"=>"14px"),
  5.         "input"    =>    array("margin"=>"0px","padding"=>"3px","border"=>"1px inset"),
  6.         "button"    =>    array("margin"=>"0px")
  7.     );


Changing default styles for label containers

The setLabelStyle() method is used to change the default styles for the label containers. The "$type" parameter is to control the alignment of the fields, if left empty, the default labels_align option will be used.

  1. # changing the default styles for the label container  for input,select and textarea
  2.     $ptc->setLabelStyle(array("float"=>false,"color"=>"red"),1);
  3.     # changing the default styles for the label container for radios and checkboxes 
  4.     $ptc->setLabelStyle(array("padding"=>"5px","vertical-align"=>false),2);
  5.     # adding the $type parameter to change the default style for a radiogroup with labels aligned right
  6.     $ptc->setLabelStyle(array("padding"=>"3px","border"=>"none"),3,"right");
The dafault styles are stored in the $_labelStyles property.
  1. # Default label container styles
  2.     $_labelStyles=array
  3.     (
  4.         # Styles for input, select and textarea
  5.         1    =>    array("left"=>array("float"=>"left","margin"=>"2px 0 0 0","width"=>"{label_width}%"),//margin:1px 0 0 0
  6.                     "right"=>array("float"=>"left","margin"=>"1px 3px 0 0",//margin:0 3px 0 0;
  7.                                     "text-align"=>"right","width"=>"{label_width}%"),
  8.                     "top"=>array()),
  9.         # Styles for checkbox and radio buttons
  10.         2    =>    array("left"=>array("vertical-align"=>"middle","border"=>"none"),
  11.                     "right"=>array("vertical-align"=>"middle","border"=>"none"),
  12.                     "top"=>array()),
  13.         # Styles for radio/checkbox group and composite fields
  14.         3    =>    array("left"=>array("float"=>"left","margin"=>"3px 0 0 0","width"=>"{label_width}%"),
  15.                     "right"=>array("float"=>"left","margin"=>"1px 3px 0 0",
  16.                                     "text-align"=>"right","width"=>"{label_width}%"),
  17.                     "top"=>array())
  18.     );


MANIPULATING HTML TEMPLATES

The customTpl() and customTpls() methods can be used to manipulate the default html template stored in the _htmlTpls property. The following examples show how we can add an id to the main container holding the form, and replacing the spacer template to add "hr".

  1. # changing the default template for the form container to add an id
  2.     $id="someID";
  3.     $ptc->customTpl(array("main_container"=>'<div style="width:{form_width}" id='.$id.'>{form}</div>'));
  4.     # replacing the main spacer template to add "<hr>" instead of "<!-- -->"
  5.     $width="90%";
  6.     $ptc->customTpl(array("spacer"=>'<div style="clear:both;height:{spacerVal}" {id}><hr style="width:'.$width.';"></div>'));
These are the default templates for all html elements used by this class.
  1. # html templates for all elements used by PtcForms component
  2.     $_htmlTpls=array
  3.     (
  4.         'select_option'        =>    '<option {attributes}>{label}</option>',
  5.         'select'            =>    '<select name="{name}" {attributes}>{options}</select>',
  6.         'textarea'            =>    '<textarea name="{name}" {attributes}>{value}</textarea>',
  7.         'input'            =>    '<input type="{type}" name="{name}" {attributes}>',
  8.         'fieldset'            =>    '<fieldset {attributes}>{label}{data} {start_tab}</fieldset>',
  9.         'form'            =>    '<form {method} {action} {attributes}>{fields}</form>',
  10.         'spacer'            =>    '<div style="clear:both;height:{spacerVal}" {id}><!-- --></div>',
  11.         'label'            =>    '<label {for} {attributes}>{label}</label>',
  12.         'legend'            =>    '<legend {attributes}>{label}</legend>',
  13.         'span'            =>    '<span {attributes}>{label}</span>',
  14.         'td'                =>    '<td align="left" valign="top">',
  15.         'table'            =>    '<table {attributes}>',
  16.         'field_container'    =>    '<div {attributes}>{label}{field} {start_tab}</div>',
  17.         'main_container'    =>    '<div style="width:{form_width}">{form}</div>'
  18.     );

ADDING FIELD EVENTS

The addFieldEvents() and addFieldEvent() methods are used to attach events to form fields.

  1. # adding a submit button
  2.     $ptc->addField("submit","submitButton");                        
  3.     # attaching an event handler to the button
  4.     $ptc->addFieldEvent("submitButton",array("onClick"=>"return false;"));
To add an event to multiple elements all at once the addValuesParams() method can be used, as shown in the next example:
  1. # adding a checkboxgroup
  2.     $ptc->addField("checkboxgroup","fieldName2[]");    
  3.     # array of values for checkboxgroup field, radiogroup and select work just the same
  4.     $select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");    
  5.     # adding the values to the checkboxgroup
  6.     $ptc->addFieldValues("fieldName2[]",$select_values);
  7.     # addvaluesparams() is used to add paramters to all values of 1 field at once, like radio/checkbox groups
  8.     # adding onmouseover to all values of checkboxgroup in 1 line
  9.     $ptc->addValuesParams("fieldName2[]","events",array("onmouseover"=>"alert(\'some text\')"));

RENDERING THE FORM

The render() method is used to build and output the form. The method accepts 2 argumets, "$attributes" and "$events" for the form.

  1. # building and printing the form
  2.     $ptc->render();
  3.     # passing some attributes and events to the form
  4.     $attributes=array("id"=>"formID","class"=>"some-class");
  5.     $events=array("onSubmit"=>"return false;");
  6.     $ptc->render($attributes,$events);
To only the build the form and store the html inside a variable, we can set the print_form option to false.
  1. # initialize the class, but don't print the form
  2.     require_once('PtcForms.php');
  3.     $ptc=new PtcForms(array("print_form"=>false));
  1. # storing the form inside a $var with "print_form" option set to false
  2.     $var=$ptc->render();

ADDING AND VALIDATING FIELDS WITH THE VALIDATOR ENGINE

The following section will try to cover the validation process (server-side) of a form, by using the class built-in engine. For validating client-side, you can use the ptcforms-validator.js ui-plugin.

Adding Fields To The Validator

The addFieldValidator() method adds the form fields to the validator engine.

These are the possible validator options:

  1. required - checks if field has a value
  2. email - checks if email is a valid format
  3. equalTo - checks if value is equal to another field specified in the value parameter
  4. number - checks if the value is numeric
  5. pattern - checks if the value matches a given regex pattern
  6. custom- some external function of your choise
If add_class_validator option is set to true, validator will add the above options as a class attribute to the fields for jquery validator plugin ptcforms-validator.js. Pattern and equalTo will be added as attributes, because they are in the _elAttributes property..
  1. # adding a password field
  2.     $ptc->addField("password","passwdField");    
  3.     # adding required as a string to the validator    
  4.     $ptc->addFieldValidator("passwdField","required");        
  5.     
  6.     # adding one more password field
  7.     $ptc->addField("password","passwdField1");            
  8.     # adding multiple validators  as array to the validator with equalTo => FieldName
  9.     $ptc->addFieldValidator("passwdField1",array("required","equalTo"=>"passwdField"));
  10.     
  11.     # some custom function that will be added to the validator(taken from ptcforms-ex1.php)
  12.     function some_func()
  13.     {
  14.         // do something with $_POST or $_GET arrays and return true or false
  15.     }
  16.     
  17.     # adding a text field
  18.     $ptc->addField("text","fieldName");    
  19.     # adding our custom function to the validator    
  20.     $ptc->addFieldValidator("fieldName",array("custom"=>"some_func"));


Validating The Form(Server Side)

The validates the form fields defined with the addFieldValidator() method, and returns an array with isValid(bool) and errors(array) as array key.

  1. # adding a submit button
  2.     $ptc->addField("submit","lg_login");    
  3.     $ptc->addFieldValue('lg_login','Login');
  4.     $ptc->fieldParentEl('lg_login',array("style"=>"text-align:right;margin-right:5px;"));
  5.     $ptc->addFieldAttributes('lg_login',array("style"=>false));    # remove default style for this field only
  6.     
  7.     $err_msg="";
  8.     if(@$_POST['lg_login'])    # check if the form was sent
  9.     {
  10.         /* VALIDATE THE FORM SERVER SIDE */
  11.         $validate=$ptc->validate();    
  12.         if(!$validate['isValid'])            # returns a bool(true/false)
  13.         {
  14.             $err_msg='<div class="errMsg" style="text-align:center;width:'.$options['form_width'].'">
  15.                                                         Wrong user ID or password!</div><br>';
  16.         }
  17.  
  18.     }
For the validator to work, remember to always run the validate() method after building the fields, otherwise the validator will not be aware of the form fields. To get around this problem, you can try to run the methods following methods against the $_POST or $_GET arrays:
  1. validateEmail()
  2. validateEqualTo()
  3. validateNumber()
  4. validatePattern()
  5. validateRequired()
This example will try to demonstrate this possibility of using these methods seperatly:
  1. $err_msg="";
  2.     if(@$_POST['lg_login'])    # check if the form was sent
  3.     {
  4.         
  5.         if(!$ptc->validateNumber("someFieldName",$_POST))    # check if value is numeric
  6.         {
  7.             // form is not valid
  8.         }
  9.         else if(!$ptc->validateEmail("otherFieldName",$_POST))    # check if value is an email
  10.         {
  11.             // form is not valid
  12.         }
  13.         else
  14.         {
  15.             // form is valid
  16.         }
  17.     }


Prev   Next
PtcDb User Guide

Documentation generated on Wed, 06 Mar 2013 23:45:41 +0100 by phpDocumentor 1.4.3