PtcForms User Guide
Html Dynamic Forms Generator/Validator - VERSION 0.8.1
Table of Contents
INTRODUCTIONThe 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 STARTEDAdd the following lines to load the class:
# initialize the class
require_once('PtcForms.php');
CLASS OPTIONSThis is the full list of options available on intialization, stored in $_defaultOptions property:
$options=array
(
"form_method" => "post", # the form method to use
"form_action" => "#", # the form action url
"form_width" => "500px", # the width for the main container
"add_class_validator" => false, # add validator classes to fields for use with jquery
"labels_align" => "left", # align labels globally(left,top,right)
"labels_width" => "40%", # the width for labels as a percentage
"style_elements" => true, # add default style to input elements to align properly
"style_labels" => true, # add default style to label elements to align properly
"style_tables" => true, # add default style to table elements to align properly
"spacer_height" => "3px", # height for the spacer between fields
"keep_values" => true, # repopulate filled fields on form submission
"print_form" => true, # print form to screen or return html only
"start_tab" => "\t", # format html code with tabs
"err_msg_level" => E_USER_WARNING,# error messages level
);
# initialize the class
require_once('PtcForms.php');
form_methodUse this option to set form method(post/get).
Default value: post (string)
form_actionThis option can be used to set form action attribute. Ex: process-form.php
Default value: # (string)
form_widthUse this option to set the width of the form.
Default value: 500px (string)
add_class_validatorThis 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_alignThis 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_widthUse "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_elementsThis 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)
# Default input styles
$_inputStyles=array
(
"radio" => array("padding"=>"0px","margin"=>"0px","vertical-align"=>"middle","width"=>"14px"),
"input" => array("margin"=>"0px","padding"=>"3px","border"=>"1px inset"),
"button" => array("margin"=>"0px")
);
style_labelsThis 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)
# Default label container styles
$_labelStyles=array
(
# Styles for input, select and textarea
1 => array("left"=>array("float"=>"left","margin"=>"2px 0 0 0","width"=>"{label_width}%"),//margin:1px 0 0 0
"right"=>array("float"=>"left","margin"=>"1px 3px 0 0",//margin:0 3px 0 0;
"text-align"=>"right","width"=>"{label_width}%"),
"top"=>array()),
# Styles for checkbox and radio buttons
2 => array("left"=>array("vertical-align"=>"middle","border"=>"none"),
"right"=>array("vertical-align"=>"middle","border"=>"none"),
"top"=>array()),
# Styles for radio/checkbox group and composite fields
3 => array("left"=>array("float"=>"left","margin"=>"3px 0 0 0","width"=>"{label_width}%"),
"right"=>array("float"=>"left","margin"=>"1px 3px 0 0",
"text-align"=>"right","width"=>"{label_width}%"),
"top"=>array())
);
style_tablesThis 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_heightThe "spacer_height" option property can be used to change the height between fields.
Default value: 3px (bool)
keep_valuesThis 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_formPrints the form or returns the output generated by the {@render()} method as a string if set to false.
Default value: true (bool)
start_tabThis 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_levelThe "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 FIELDSThe 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:
- text
- password
- radio
- checkbox
- checkboxgroup
- radiogroup
- select
- fieldset
- composite (for complex field layouts)
- custom (any html code can be passed as value)
- 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 FieldThis is how we can add a text field.
# adding a text field
# adding a label to the text field
# adding a value that will be shown inside the input
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 FieldThis is how wed can add a select field, to make an option selected you can use the "=>" operator.
# adding a select field
# adding a label to the select field
# array of values for the select, radiogroup and checkboxgroup work just the same
$select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");
# adding the values to the select field
# setting attribute checked on 1 select option
# works for all fields inside 1 level above like
# composites,radio/checkbox groups fieldsets and selects
The following fields can be added like shown in the example above: select, radiogroup, checkboxgroup.
Adding a CheckboxgroupThis 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.
# adding a checkboxgroup
$ptc->addField("checkboxgroup","fieldName2[]");
# adding a label to the checkboxgroup
# array of values for checkboxgroup field, radiogroup and select work just the same
$select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");
# adding the values to the checkboxgroup
# setting the labels to apper at the right of the boxes, default form alignment is left
# addvaluesparams() is used to add paramters to all values of 1 field at once, like radio/checkbox groups
$ptc->addValuesParams("fieldName2[]","labelOptions",array("align"=> "right"));
# setting 2 columns for 3 values previously added, default for radio/checkbox group is 1
# setting attribute checked on 1 checkbox
The following fields can be added like shown in the example above: select, radiogroup, checkboxgroup.
Adding a CompositeComposite 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.
# adding a composite
$ptc->addField("composite","fieldName3");
# adding the previously created text and select fields to to the composite
$ptc->addFieldValue("fieldName3",array("fieldName","fieldName1"));
# setting the composite for 1 column only, default is all fields inline
The following fields can be added like shown in the example above: fieldset, composite.
Adding a FieldsetFieldsets are used for previously created fields, that can be added as values. The label will act as legend.
# adding a fieldset
$ptc->addField("fieldset","fieldName4");
# adding some text to the the fieldset legend
# adding the previously created composite and checkboxgroup fields to to the fieldset
$fieldset_values=array("fieldName3","fieldName2[]");
# adding previously created fields as values to the fieldset
The following fields can be added like shown in the example above: fieldset, composite.
Adding a Custom Field for a SpacerThis 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.
# creating a custom field for a space
# adding the a spacer to the custom field, any html can be passed as value
# for custom type only addfield() and addfieldvalue() are allowed
ADDING LABELSThe addFieldLabel() method adds a label to the field specified by the $fieldName param.
We can add a label to a field like this:
# adding a text field
# adding a label to the text field
# adding a value that will be shown inside the input
We can add a label to the fieldset aswell:
# adding a fieldset
$ptc->addField("fieldset","fieldName4");
# adding some text to the the fieldset legend
# adding the previously created composite and checkboxgroup fields to to the fieldset
$fieldset_values=array("fieldName3","fieldName2[]");
# adding previously created fields as values to the fieldset
ADDING VALUES TO FIELDSThe 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 stringthe following fields accept a value as a string:
- text
- textarea
- password
- radio
- checkbox
- custom (any html code can be passed as value)
- submit
This is how we can add a value to a field as a string:
Adding values as an arraythe following fields accept an array as a field value:
- select
- radiogroup
- checkboxgroup
The following examples demostrate how we can add an array as a field value:
# adding a select field
# adding a label to the select field
# array of values for the select, radiogroup and checkboxgroup work just the same
$select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");
# adding the values to the select field
# adding a checkboxgroup
$ptc->addField("checkboxgroup","fieldName2[]");
# adding a label to the checkboxgroup
# array of values for checkboxgroup field, radiogroup and select work just the same
$select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");
# adding the values to the checkboxgroup
Adding fields as array of values(composite,fieldset)the following fields accept an array with previously created field names as values:
- fieldset
- composite
The following examples demostrate how we can add previously created fields as an array of values:
# adding a composite
$ptc->addField("composite","fieldName3");
# adding the previously created text and select fields to to the composite
$ptc->addFieldValue("fieldName3",array("fieldName","fieldName1"));
# setting the composite for 1 column only, default is all fields inline
# adding a fieldset
$ptc->addField("fieldset","fieldName4");
# adding some text to the the fieldset legend
# adding the previously created composite and checkboxgroup fields to to the fieldset
$fieldset_values=array("fieldName3","fieldName2[]");
# adding previously created fields as values to the fieldset
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 VALUESThe 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:
# adding a checkboxgroup
$ptc->addField("checkboxgroup","fieldName2[]");
# array of values for checkboxgroup field, radiogroup and select work just the same
$select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");
# adding the values to the checkboxgroup
# addvaluesparams() is used to add paramters to all values of 1 field at once, like radio/checkbox groups
# adding onmouseover to all values of checkboxgroup in 1 line
$ptc->addValuesParams("fieldName2[]","events",array("onmouseover"=> "alert(\'some text\')"));
# setting the labels to apper at the right of the boxes, default form alignment is left
$ptc->addValuesParams("fieldName2[]","labelOptions",array("align"=> "right"));
Possible options for the "$type" parameter are stored in the _storageKeys property:
# possible storage keys for addValuesParams()
$_storageKeys=array("events","attributes","validate","label","labelOptions","parentEl");
.
ADDING HTML ATTRIBUTES TO ELEMENTSThis 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.
# these are the default elements attributes, more can be added with the addElAttributes() method
$_elAttributes=array('class','id','style','value','maxlength','size','disabled','checked','target','events',
'title','selected','cols','rows','equalTo','border','pattern','cellpadding','cellspacing');
Adding attributes to fieldsThe addFieldAttributes() method is used to add html attributes to form fields.
# adding a textarea field
$ptc->addField("textarea","textAreaField");
# adding html attributes to the textarea, set style=>false to remove default styles for 1 field
$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:
# setting attribute checked on 1 checkbox
Adding attributes to label containerThe addLabelOptions() method is used to add html attributes to the label container.
# setting a different style and changing alignment for a label container
$ptc->labelOptions("someFieldName"=>array("align"=>"top","style"=>"margin:10px"));
# setting an id and a class for the label container, and adding style=>false to remove the default label container style
$ptc->labelOptions("someFieldName"=>array("id"=>"someID","class"=>"some-class","style"=>false));
Adding attributes to field containerThe fieldParentEl() method is used to add html attributes to the field container.
# adding a submit button
$ptc->addField("submit","submitButton");
# adding html attributes to the parent div of a submit button,
# set "style"=>false to remove default styles for 1 field
$ptc->fieldParentEl("submitButton",array("style"=> "text-align:right;"));
Extending the compiler with custom attributesThe 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:
# adding an attribute to the the _elAttributes property
$ptc->AddElAttributes("default-value");
# adding an array of attributes
$ptc->AddElAttributes(array("default-value","tabindex"));
CHANGING DEFAULT STYLES APPLIED TO ELEMENTSThe 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 fieldsThe setInputStyle() method is used to change the default styles for the fields.
# changing the default styles for radio/checkbox fields, removing "vertical-align" property
$ptc->setInputStyle(array("margin"=> "0 10px 0 0","vertical-align"=> false),"radio");
# changing the default styles for input fields
$ptc->setInputStyle(array("padding"=> "3px","border"=> "none"),"input");
The dafault styles are stored in the $_inputStyles property.
# Default input styles
$_inputStyles=array
(
"radio" => array("padding"=>"0px","margin"=>"0px","vertical-align"=>"middle","width"=>"14px"),
"input" => array("margin"=>"0px","padding"=>"3px","border"=>"1px inset"),
"button" => array("margin"=>"0px")
);
Changing default styles for label containersThe 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.
# changing the default styles for the label container for input,select and textarea
# changing the default styles for the label container for radios and checkboxes
$ptc->setLabelStyle(array("padding"=> "5px","vertical-align"=> false),2);
# adding the $type parameter to change the default style for a radiogroup with labels aligned right
$ptc->setLabelStyle(array("padding"=> "3px","border"=> "none"),3,"right");
The dafault styles are stored in the $_labelStyles property.
# Default label container styles
$_labelStyles=array
(
# Styles for input, select and textarea
1 => array("left"=>array("float"=>"left","margin"=>"2px 0 0 0","width"=>"{label_width}%"),//margin:1px 0 0 0
"right"=>array("float"=>"left","margin"=>"1px 3px 0 0",//margin:0 3px 0 0;
"text-align"=>"right","width"=>"{label_width}%"),
"top"=>array()),
# Styles for checkbox and radio buttons
2 => array("left"=>array("vertical-align"=>"middle","border"=>"none"),
"right"=>array("vertical-align"=>"middle","border"=>"none"),
"top"=>array()),
# Styles for radio/checkbox group and composite fields
3 => array("left"=>array("float"=>"left","margin"=>"3px 0 0 0","width"=>"{label_width}%"),
"right"=>array("float"=>"left","margin"=>"1px 3px 0 0",
"text-align"=>"right","width"=>"{label_width}%"),
"top"=>array())
);
MANIPULATING HTML TEMPLATESThe 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".
# changing the default template for the form container to add an id
$id="someID";
$ptc->customTpl(array("main_container"=> '<div style="width:{form_width}" id='. $id. '>{form}</div>'));
# replacing the main spacer template to add "<hr>" instead of "<!-- -->"
$width="90%";
$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.
# html templates for all elements used by PtcForms component
$_htmlTpls=array
(
'select_option' => '<option {attributes}>{label}</option>',
'select' => '<select name="{name}" {attributes}>{options}</select>',
'textarea' => '<textarea name="{name}" {attributes}>{value}</textarea>',
'input' => '<input type="{type}" name="{name}" {attributes}>',
'fieldset' => '<fieldset {attributes}>{label}{data} {start_tab}</fieldset>',
'form' => '<form {method} {action} {attributes}>{fields}</form>',
'spacer' => '<div style="clear:both;height:{spacerVal}" {id}><!-- --></div>',
'label' => '<label {for} {attributes}>{label}</label>',
'legend' => '<legend {attributes}>{label}</legend>',
'span' => '<span {attributes}>{label}</span>',
'td' => '<td align="left" valign="top">',
'table' => '<table {attributes}>',
'field_container' => '<div {attributes}>{label}{field} {start_tab}</div>',
'main_container' => '<div style="width:{form_width}">{form}</div>'
);
ADDING FIELD EVENTSThe addFieldEvents() and addFieldEvent() methods are used to attach events to form fields.
# adding a submit button
$ptc->addField("submit","submitButton");
# attaching an event handler to the button
$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:
# adding a checkboxgroup
$ptc->addField("checkboxgroup","fieldName2[]");
# array of values for checkboxgroup field, radiogroup and select work just the same
$select_values=array("yes"=>"Yes","no"=>"No","maybe"=>"Maybe");
# adding the values to the checkboxgroup
# addvaluesparams() is used to add paramters to all values of 1 field at once, like radio/checkbox groups
# adding onmouseover to all values of checkboxgroup in 1 line
$ptc->addValuesParams("fieldName2[]","events",array("onmouseover"=> "alert(\'some text\')"));
RENDERING THE FORMThe render() method is used to build and output the form.
The method accepts 2 argumets, "$attributes" and "$events" for the form.
# building and printing the form
# passing some attributes and events to the form
$attributes=array("id"=>"formID","class"=>"some-class");
$events=array("onSubmit"=>"return false;");
$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.
# initialize the class, but don't print the form
require_once('PtcForms.php');
$ptc= new PtcForms(array("print_form"=> false));
# storing the form inside a $var with "print_form" option set to false
ADDING AND VALIDATING FIELDS WITH THE VALIDATOR ENGINEThe 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 ValidatorThe addFieldValidator() method adds the form fields to the validator engine.
These are the possible validator options:
- required - checks if field has a value
- email - checks if email is a valid format
- equalTo - checks if value is equal to another field specified in the value parameter
- number - checks if the value is numeric
- pattern - checks if the value matches a given regex pattern
- 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..
# adding a password field
$ptc->addField("password","passwdField");
# adding required as a string to the validator
# adding one more password field
$ptc->addField("password","passwdField1");
# adding multiple validators as array to the validator with equalTo => FieldName
# some custom function that will be added to the validator(taken from ptcforms-ex1.php)
function some_func()
{
// do something with $_POST or $_GET arrays and return true or false
}
# adding a text field
# adding our custom function to the validator
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.
# adding a submit button
$ptc->fieldParentEl('lg_login',array("style"=> "text-align:right;margin-right:5px;"));
$ptc->addFieldAttributes('lg_login',array("style"=> false)); # remove default style for this field only
$err_msg="";
if(@$_POST['lg_login']) # check if the form was sent
{
/* VALIDATE THE FORM SERVER SIDE */
if(!$validate['isValid']) # returns a bool(true/false)
{
$err_msg='<div class="errMsg" style="text-align:center;width:'.$options['form_width'].'">
Wrong user ID or password!</div><br>';
}
}
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:
- validateEmail()
- validateEqualTo()
- validateNumber()
- validatePattern()
- validateRequired()
This example will try to demonstrate this possibility of using these methods seperatly:
$err_msg="";
if(@$_POST['lg_login']) # check if the form was sent
{
if(!$ptc->validateNumber("someFieldName",$_POST)) # check if value is numeric
{
// form is not valid
}
else if(!$ptc->validateEmail("otherFieldName",$_POST)) # check if value is an email
{
// form is not valid
}
else
{
// form is valid
}
}
Prev |
|
Next |
PtcDb User Guide |
|
|
|
|