PhpToolCase
Api Documentation Version 0.9.2
Dynamic HTML Form Generator & Validator (PtcForm)

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. The component can also be used with the PtcEvent class, to add event listeners to process validation and output generation. This tool 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
  • Event listeners to process validation and output generation
  • Uses the PtcDebug component to debug the html generation and validation process



Getting Started

To use this component, you just need to require and initialize the class:

// initialize the class
require_once( 'PtcForms.php' );
$form = new PtcForms( );



Class Options

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

$_defaultOptions = 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,none)
'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
'debug_category' => 'PtcForm' , // default category for the PtcDebug class
'event_class' => '\PtcEvent' // event class parameter
// initialize the class with some options
require_once( 'PtcForms.php' );
$form = new PtcForms( $options );

The following paragraphs will explain in details these options and the usage.

form_method

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

Default value: # (string)


form_action

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

Default value: 500px (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 & 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 layout migt not be as expected. You can refer to 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 PtcForm::$_inputStyles property, and can be manipulated with the PtcForm::setInputStyle() method.

$_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' )
);

See Changing default styles for fields for a detailed usage.

Default value: true (bool)


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 PtcForm::$_labelStyles property, and can be manipulated with the PtcForm::setLabelStyle( ) method.

$_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' )
);

See Changing Default Styles For Label Containers for a detailed usage.

Default value: true (bool)


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 can be used to change the height between fields.

Default value: 3px (string)


keep_values

This options is used to reload 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 PtcForm::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 you would lneed 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)


default_category

The "default_category" is used for the PtcDebug class to set a category for the messages panel. Change it to customize the debug output.

Default value: PtcForm (string)


event_class

The "event_class" option can be used to change the event class that will work with observers. Change this option if the PtcEvent component is under a namespace or it has been extended.

See Using Observers to understand how events work.

Default value: \PtcEvent (string)

Note
For this option to work, the PtcEvent component needs to be present. See Event Dispatcher Component (PtcEvent) to learn more about this component.

Field Parameters

The following paragraph will cover all possible parameters that can be passed to the PtcForm::addElement( ) method, and their usage.

// addding a text field
$form->addElement( array
(
'name' => 'fieldName' , // mandatory, will throw a warning if not present
'type' => 'text' , // text is default if "type" is not present
'label' => 'LabelText' // the text for the label
) );

Here is a list of all possibile parameters that can be passed to the PtcForm::addElement( ) method as array keys for the "$params" parameter:

Some of these parameters can be added to field values like select and radio / checkbox groups, with "[brackets]" (Ex.: attributes[ ]).

See Using [brackets] To Add Parameters To Field Values for detailed usage.

The following sections, will explain in details the usage of these parameters:

name

This parameter defines the field name and is mandatory, the class will throw a warning if not set, and the field will not be processed by the compiler.

Type: string


type

This parameter defines the field type. If not set, "text" will be used.

Possible field types:

  • text (default)
  • password
  • radio
  • checkbox
  • checkboxgroup
  • radiogroup
  • textarea
  • select
  • fieldset
  • composite (for complex field layouts)
  • custom (any html code can be passed as value)
  • submit

Type string


label

Use this parameter to set the the text for the label of the field.

Type string


attributes

Adds html attributes to the field, all attributes are stored in PtcForm::$_elAttributes property. New attributes can be added with the PtcForm::addElAttribute() and PtcForm::addElAttributes() methods, see Extending The Compiler With Custom Attributes.

See Adding Attributes To Fields for examples and detailed usage.

Type array


labelOptions

Adds html attributes to the label container, all attributes are stored in PtcForm::$_elAttributes property. New attributes can be added with the PtcForm::addElAttribute() and PtcForm::addElAttributes() methods, see Extending The Compiler With Custom Attributes.

See Adding Attributes To Label Containers for examples and detailed usage.

Type array


parentEl

Adds html attributes to the parent container of the field, all attributes are stored in PtcForm::$_elAttributes property. New attributes can be added with the PtcForm::addElAttribute( ) and PtcForm::addElAttributes( ) methods, see Extending The Compiler With Custom Attributes.

See Adding Attributes To Field Containers for examples and detailed usage.

Type array


events

The events parameter can be used to add javascipt events to the fields.

the following field types are supported:

  • text
  • password
  • textarea
  • submit
  • select
  • radio
  • checkbox
  • checkboxgroup (will be added to all values)
  • radiogroup (will be added to all values)

See Adding JavScript Events for detailed usage.

Type array


validate

Use this parameter to add the field 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
Note
Any other value will be interpreted as a custom function.

The following field types are supported:

  • text
  • password
  • textarea
  • submit
  • select
  • radio
  • checkbox
  • checkboxgroup (will be added to all values)
  • radiogroup (will be added to all values)

See Adding Fields To The Validator for example usage.

Type string|array


values

The parameter "values" is used to add values for the following fields:

  • select
  • checkboxgroup
  • radiogroup
  • composite
  • fieldset

See Adding Values As Array (select, radiogroup, checkboxgroup) for examples on how to add values for select,radiogroup and checkboxgroup.

See Adding Fields As Array Of Values (composite, fieldset) for examples on how to add values for composite and fieldset.

Type array


value

The parameter "value" can be used to add the value as a string for the following field

  • text
  • password
  • textarea
  • submit
  • radio
  • checkbox
  • custom (any html code can be passed as value)

See Adding Values As A String for example usage.

Type string


Adding Fields Examples

The PtcForm::addElement() method is used to add form fields. Works with all input types, but some extra parameters can be passed aswell to create custom html. The "$params" paramater is used to pass the configuration for the field to the method as an array. See Field Parameters paragraph, for all possibile parameters.

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

Adding Text Fields

Here's a quick example on how to add text fields:

// addding a text field
$form->addElement( array
(
'name' => 'fieldName' , // mandatory, will throw a warning if not present
'type' => 'text' , // text is default if "type" is not present
'label' => 'LabelText' // the text for the label
) );

The following fields can be created like shown in the example above as they do not require a "value":

  • text
  • radio
  • checkbox
  • textarea
  • password
  • submit

The following fields require a "value", or the class will throw a warning:

  • select
  • radiogroup
  • checkboxgroup
  • composite
  • fieldset
  • custom

Adding Select Fields

Here's an example on how to add select elements:

// preparing the select options
$values = array
(
'' => 'Choose' , // adding an empty option
'enquiry' => 'Enquiry' ,
'information' => 'Information' ,
'billing' => 'Billing' ,
'other' => 'Other'
);
// adding a select field
$form->addElement(array
(
'name' => 'fieldName1' ,
'type' => 'select' ,
'label' => 'LabelText' ,
'values' => $values // adding previously created array with values
) );

To make an option selected you can use "[brackets]", see Using [brackets] To Add Parameters To Field Values.

Adding Checkboxgroups / Radiogroups

The following example shows how to add checkboxgroups, adding radiogroups is just the same:

// adding a checkboxgroup
$form->addElement( array
(
'type' => 'checkboxgroup' ,
'name' => 'fieldName5' ,
'values' => array( 'yes' => 'Yes !!! (please)' , 'no' => 'No (thank you)' ),
'attributes' => array( 'cols'=>2 ) // display values inline
) );

To make a checkbox checked you can use "[brackets]", see Using [brackets] To Add Parameters To Field Values. note the "cols" attribute controls how many columns the group will have. The default value is 1.

Adding Composite Fields

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.

// adding a composite field for previously created fields
$form->addElement( array
(
'name' => 'fieldName2' ,
'type' => 'composite' ,
'values' => array( 'fieldName' , 'fieldName1' ) // previously created field names
) );

The following fields can be added like shown in the example above: fieldset, composite.

Note
the "cols" attribute controls how many columns the group will have. The default value is "inline".

Adding Custom Fields

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

// adding a spacer
$form->addElement( array
(
'type' => 'custom' ,
'name' => 'spacer1' ,
'value' => $form->addSpacer( '3px' )
) );

The custom field type will only accept the following parameters:

  • name
  • type
  • value

Any other parameter will be dropped silently.


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 PtcForm::$_elAttributes property. New attributes can be added with the PtcForm::addElAttribute() and PtcForm::addElAttributes() methods, see Extending The Compiler With Custom Attributes.

$_elAttributes = array
(
'class' , 'id' , 'style' , 'value' , 'maxlength' , 'minlength' ,'cellpadding' ,
'cellspacing' , 'size' , 'disabled' , 'checked' , 'target' , 'align' , 'events' ,
'title' , 'selected' , 'cols' , 'rows' , 'equalTo' , 'border' , 'pattern'
);

Adding Attributes To Fields

The parameter "attributes" is used to add html attributes to form fields:

// adding a textarea field
$form->addElement( array
(
'type' => 'textarea' ,
'name' => 'fieldName8' ,
'label' => 'labelText' ,
// adding html attributes to the textarea, set 'style=>false' to remove default styles for 1 field
'attributes' => array( 'id' => 'fieldID' , 'class' => 'some-class' , 'style' => false )
) );

To add attributes to values for select and radio/checkbox groups we can use "[brackets]" like shown in the next example:

// preparing the select options
$values = array
(
'' => 'Choose' , // adding an empty option
'enquiry' => 'Enquiry' ,
'information' => 'Information' ,
'billing' => 'Billing' ,
'other' => 'Other'
);
$form->addElement( array
(
'name' => 'fieldName10' ,
'type' => 'select' ,
'label' => 'LabelText' ,
'values' => $values ,
'attributes[]' => array( 'class' => 'someClass' ) , // will add the class to all select options
'attributes[enquiry]' => array( 'selected' => 1 ) // making 1 option selected
) );

See Using [brackets] To Add Parameters To Field Values for more details.

Adding Attributes To Label Containers

The parameter labelOptions is used to add html attributes to the label container:

// adding a textarea field
$form->addElement( array
(
'type' => 'textarea' ,
'name' => 'fieldName11' ,
'label' => 'labelText' ,
// setting a different style and changing alignment for a label container
'labelOptions' => array( 'align' => 'top' , 'style' => 'margin:10px' )
) );

To add attributes to label containers of the field values for radio/checkbox groups we can use "[brackets]" like shown in the next example:

// adding a radiogroup
$form->addElement( array
(
'type' => 'radiogroup' ,
'name' => 'fieldName12' ,
'values' => array( 'yes' => 'Yes !!! (please)' , 'no' => 'No (thank you)' ) ,
'labelOptions' => array( 'style' => false ) , // removing default style for label container of the field
'labelOptions[]' => array( 'align' => 'top' ) , // aligning labels of all values to the top
'labelOptions[yes]' => array( 'class' => 'some-class' ) // adding a class to the label container of 1 value
) );

See Using [brackets] To Add Parameters To Field Values for more details.

Adding Attributes To Field Containers

The parameter parentEl is used to add html attributes to the field container:

// adding a submit button
$form->addElement(array
(
'type' => 'submit' ,
'name' => 'fieldName13' ,
'value' => 'Submit' , // adding a value to the field
'parentEl' => array( 'style' => 'text-align:right;' ) // adding style to the parent container
) );

To add attributes to the parent containers of the field values for radio/checkbox groups we can use "[brackets]" like shown in the next example:

// adding a checkboxgroup
$form->addElement(array
(
'type' => 'checkboxgroup' ,
'name' => 'fieldName14' ,
'values' => array( 'yes' => 'Yes !!! (please)' , 'no' => 'No (thank you)' ) ,
'parentEl[]' => array( 'class' => 'some-class' ) , // adding a class to the parent container of all values
'parentEl[yes]' => array( 'id' => 'someID' ) // adding an id to the parent container of 1 value
) );

See Using [brackets] To Add Parameters To Field Values for more details.

Extending The Compiler With Custom Attributes

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

// adding an attribute to the the $_elAttributes property
$form->AddElAttributes( 'default-value' );
// adding an array of attributes
$form->AddElAttributes( array( 'default-value' , 'tabindex' ) );



Changing Default Styles Applied To Elements

The methods PtcForm::setInputStyle( ) and PtcForm::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 PtcForm::setInputStyle( ) method is used to change the default styles for the fields:

// changing the default styles for radio/checkbox fields, removing "vertical-align" property
$form->setInputStyle( array( 'margin' => '0 10px 0 0' , 'vertical-align' => false ) , 'radio' );
// changing the default styles for input fields
$form->setInputStyle( array( 'padding' => '3px' , 'border' => 'none' ) , 'input' );

The default styles are stored in the PtcForm::$_inputStyles property.

$_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 Containers

The PtcForm::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
$form->setLabelStyle( array( 'float' => false , 'color' => 'red' ) ,1 );
// changing the default styles for the label container for radios and checkboxes
$form->setLabelStyle( array( 'padding' => '5px' , 'vertical-align' => false ) , 2 );
// adding the $type parameter to change the default style for a radiogroup with labels aligned right
$form->setLabelStyle( array( 'padding' => '3px' , 'border' => 'none' ) , 3 , 'right' );

The default styles are stored in the PtcForm::$_labelStyles property:

$_labelStyles = array
(
// Styles for input, select and textarea
1 => array( 'left' => array( 'float' => 'left' , 'margin' => '2px 0 0 0' , 'width' => '{label_width}%' ) ,
'right' => array( 'float' => 'left' , 'margin' => '1px 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( ) )
);



Using Closures With Field Parameters

The PtcForm class accepts closures as field parameters with the PtcForm::addElement( ) method. The following example shows how we can take advantage of this feature:

$form->addElement( array
(
'type' => 'select' ,
'name' => 'usr_sel_day' ,
'label' => 'Which day of the month were you born?' ,
// using a closure to create an array of values for the "values" parameter
'values' => function( )
{
$days = array( '' => null );
foreach ( range( 1 , 31 ) as $day )
{
$day = ( strlen( $day ) === 1 ) ? '0' . $day : $day;
$days[ $day ] = $day;
}
return $days;
}
) );



Manipulating Html Templates

The PtcForm::customTpl() and PtcForm::customTpls() methods can be used to manipulate the default html templates stored in the PtcForm::$_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';
$form->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%";
$form->customTpl( array( 'spacer' => '<div style="clear:both;height:{spacerVal}" {id}><hr style="width:' . $width . ';"></div>' ) );

The html templates are stored in the PtcForm::$_htmlTpls property:

// 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 Values To Fields

The parameters values and value are used to add values to form fields. An array is passed for select, checkboxgroup, radiogroup, fieldset and composite fields. The rest of the fields use a string as value.

Adding Values As A String

The parameter value can be used to add a value as a string for the following fields:

  • text
  • radio
  • checkbox
  • textarea
  • password
  • submit
  • custom (any html code can be passed as value)

This is how we can add a value to a field as a string:

// adding a submit button
$form->addElement( array
(
'type' => 'submit' ,
'name' => 'fieldName3' ,
'value' => 'Submit' // adding a value to the field
) );

The same result can be achieved with the attributes parameter:

// adding a submit button
$form->addElement( array
(
'type' => 'submit' ,
'name' => 'fieldName4' ,
'attributes' => array( 'value' => 'Submit' ) // same as the "value" parameter
) );

Adding Values As Array (select, radiogroup, checkboxgroup)

The parameter values can be used to add an array of values for the following fields:

  • select
  • radiogroup
  • checkboxgroup

The following examples demonstrate how values can be added as an array, with values as array keys and labels as array values:

// preparing the select options
$values = array
(
'' => 'Choose' , // adding an empty option
'enquiry' => 'Enquiry' ,
'information' => 'Information' ,
'billing' => 'Billing' ,
'other' => 'Other'
);
// adding a select field
$form->addElement( array
(
'name' => 'fieldName1',
'type' => 'select',
'label' => 'LabelText',
'values' => $values // adding previously created array with values
) );

To add parameters to values "[brackets]" can be used, see Using [brackets] To Add Parameters To Field Values for more details.


Adding Fields As Array Of Values (composite, fieldset)

The parameter"values can be used to add an array with previously created field names as values for the following fields:

  • fieldset
  • composite

The following examples demostrate how values can be added as an array with the names of the previously created fields as values:

// adding a composite field for previously created fields
$form->addElement( array
(
'name' => 'fieldName2' ,
'type' => 'composite' ,
'values' => array( 'fieldName' , 'fieldName1' ) // previously created field names
) );

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.


Using [brackets] To Add Parameters To Field Values

The following fields allow the use of "[brackets]" to add parameters to the values:

  • select
  • radiogroup
  • checkboxgroup

the select input only accepts "[brackets]" for the attributes parameter:

// preparing the select options
$values = array
(
'' => 'Choose' , // adding an empty option
'enquiry' => 'Enquiry' ,
'information' => 'Information' ,
'billing' => 'Billing' ,
'other' => 'Other'
);
// adding a select field
$form->addElement(array
(
'name' => 'fieldName6' ,
'type' => 'select' ,
'label' => 'LabelText' ,
'values' => $values ,
'attributes[]' => array( 'class' => 'someClass' ) // will add the class to all select options
) );

Radio/checkbox groups accept the following parameters with "[brackets]":

To interact with all values just use []. To interact with only 1 value use the array key of the respective value like shown in the next example:

// adding a radiogroup
$form->addElement( array
(
'type' => 'radiogroup' ,
'name' => 'fieldName7' ,
'values' => array( 'yes' => 'Yes !!! (please)' , 'no' => 'No (thank you)' ) ,
'labelOptions[]' => array( 'align' => 'top' ) , // aligning labels of all values to the top
'attributes[yes]' => array( 'checked' => 1 ) , // making 1 value checked
) );

The only 2 exceptions are events and validate which will be added to all values also without "[brackets]", as no validation or events can be attached to the main field.


Adding JavScript Events

The events parameter is used to attach javascript events to form fields:

// adding a submit button
$form->addElement(array
(
'type' => 'submit' ,
'name' => 'fieldName15' ,
'events' => array( 'onClick' => 'return false;' ) // attaching js events to the field
) );
Note
radio/checkboxgroup will add js events to all field values.

To add js events to 1 value for radio/checkboxgroup use "[brackets]", as shown in the next example:

// adding a checkboxgroup
$form->addElement( array
(
'type' => 'checkboxgroup' ,
'name' => 'fieldName16' ,
'values' => array( 'yes' => 'Yes !!! (please)' , 'no' => 'No (thank you)' ) ,
'events[yes]' => array( 'onClick' => 'return false;' ) // attaching js events to 1 field value
) );

See Using [brackets] To Add Parameters To Field Values for more details over this option.


Rendering The Form

The PtcForm::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
$form->render( );
// passing some attributes and events to the form
$attributes=array( 'id' => 'formID' , 'class' => 'some-class' );
$events=array( 'onSubmit' => 'return false;' );
$form->render( $attributes , $events );

To only 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' );
// using "print_form" to store the form html output
$form = new PtcForms( array( 'print_form' => false ) );
// storing the form inside a $var
$var=$form->render( );



Adding & 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. At the bottom of the page you will find intructions on how to set up the client-side validation with jquery.

Adding Fields To The Validator

The validate parameter adds the form fields to the validator engine.

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, as they are in the PtcForm::$_elAttributes property.

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

Here's an example on how to use these parameters:

// addding a password field
$form->addElement( array
(
'name' => 'passwdField' ,
'type' => 'password' ,
'label' => 'LabelText' ,
'validate' => 'required' // adding required for this field
) );
// addding 1 more password field
$form->addElement(array
(
'name' => 'passwdField1' ,
'type' => 'password' ,
'label' => 'LabelText' ,
'validate' => array( 'required' , 'equalTo' => 'passwdField' ) // adding multiple validators for this field
) );

Any other value will be interpreted as a custom function:

// 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
$form->addElement(array
(
'name' => 'fieldName17' ,
'type' => 'text' ,
'label' => 'LabelText' ,
'validate' => 'some_func'
) );

Radio/checkbox groups will add validation to all field values, to add validation to 1 value for radio/checkboxgroup use "[brackets]":

// adding a checkboxgroup
$form->addElement(array
(
'type' => 'checkboxgroup' ,
'name' => 'fieldName16' ,
'values' => array( 'yes' => 'Yes !!! (please)' , 'no' => 'No (thank you)' ) ,
'validate[yes]' => 'required' // adding validation to 1 checkbox only
) );

See Using [brackets] To Add Parameters To Field Values for more details.

Validating The Form (Server Side)

The PtcForm::validate( ) method validates the form fields defined with the validate parameter, and returns an array with isValid(bool) and errors(array) as array keys.

// adding a submit button
$form->addElement( array
(
'name' => 'lg_login',
'type' => 'submit',
'value' => 'Login'
) );
$err_msg = '';
if ( @$_POST[ 'lg_login' ] ) // check if the form was sent
{
// VALIDATE THE FORM SERVER SIDE
$validate = $form->validate( );
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 call the PtcForm::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 following methods against the $_POST or $_GET arrays:

$err_msg = '';
if ( @$_POST[ 'lg_login' ] ) // check if the form was sent
{
if ( !$form->validateNumber( 'someFieldName' , $_POST ) ) // check if value is numeric
{
// form is not valid
}
else if ( !$form->validateEmail( 'otherFieldName' , $_POST ) ) // check if value is an email
{
// form is not valid
}
else
{
// form is valid
}
}



Using Observer Events

The PtcForm component can be used with the PtcEvent class, to add event observers to process validation and output generation.

Here follows a list with all event observers and possible arguments, when they are fired:

  • error ( &$object->_validate , &$object->_errMsg , $object ), called on form validation failure
  • valid ( &$object->_validate , &$object->_errMsg , $object ), called on form validation success
  • submit ( $button_name , $object ) called on form submission
  • adding ( $field_name , $field_type , &$params , $object ), called every time an element is about to be added
  • added ( $field_name , &$object->_fields[ $field_name ] , $object ), called after each element is added
  • rendering ( &$container , $this ), called before form is rendered
  • rendered ( &$container , $object ), called after the form is rendered
  • building ( $k , &$object->_fields[ $k ] , $this ), called before each field html container is created
  • built ( $k , &$fields , $this ), called after each field html container is created
  • validating ( $key , &$k , &$method ), called before each field is about to be validated
  • validated ( $k , $method , &$errs ), called after each field has been validated

To use these observer events, add them as static methods to your extended class:

class myObserver
{
// observer events, static methods are used
public static function submit( $fieldName , $obj ) // form submit event, run validator here
{
$obj->validate( );
}
public static function error( $result , $errMsg , $obj ) // form is not valid, add an error msg
{
$errMsg = '<div class="errMsg" style="text-align:center;width:' .
$obj->getOption( 'form_width' ) . '">Something went wrong. Please review the form!</div><br>';
}
public static function valid( $result , $msg , $obj ) // form is valid, let's redirect the user to the login area
{
// the form is valid do something here
// adding a success message to the form
$msg = '<div class="errMsg" style="text-align:center;width:' .
$obj->getOption( 'form_width' ) . '">Form has been sent!</div><br>';
}
}

On form submission, the "submit" event will be triggered, which will validate the form. If the form is not valid, the "error" event will be triggered. The "valid" event will fire instead, if form was valid.

Observers can be registered with the method PtcForm::observe( ):

$form = new PtcForm( );
// register the class as observer
$form->observe( 'myObserver' );



Adding Options On Initialization

To add options on initialization, add the method boot( ) to your extended class:

class contactForm extends PtcForm
{
// we can override default options property in our extended class
protected $_options = array
(
'add_class_validator' => true ,
'form_width' => '400px' ,
'labels_align' => 'right' ,
'spacer_height' => '10px'
);
// using the boot method to add event listeners to the class
public function boot( )
{
// changing the default styles for input fields
$this->setInputStyle( array( 'padding' => '3px' , 'border' => 'none' ) , 'input' );
// we could do a databse query to retrieve form values here
}
}
Note
The "boot( )" method will be called by the contructor.

Adding Form Fields On Initialization

Fields can be added directly inside an extended class, which is convenient if you want to use the form multiple times.

Add the method formFields( ) to your class , and configure your form fields inside:

class contactForm extends PtcForm
{
// method that will build the fields , will be called by constructor
public function formFields( )
{
// adding a text field
$this->addElement( array
(
'name' => 'ct_firstname' ,
'label' => 'Firstname:*' ,
'validate' => 'required'
) );
// adding a text field
$this->addElement( array
(
'name' => 'ct_lastname' ,
'label' => 'Lastname:*' ,
'validate' => 'required'
) );
}
}
// constructor will call the method formFields( )
$form = new contactForm( );