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

PtcForms User Guide

Html Dynamic Forms Generator/Validator - VERSION 0.8.3

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.     $form=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.         'debug_category'        =>    'PtcForms' // default category for the PtcDebug class
  18.     );
  19.     
  20.     // initialize the class
  21.     require_once('PtcForms.php');
  22.     $form=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 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'),//padding:2px;
  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 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

Default value: PtcForms (string)


FIELD PARAMETERS

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

  1. // addding a text field
  2.     $form->addElement(array
  3.     (    
  4.         'name'    =>        'fieldName',    // mandatory, will throw a warning if not present
  5.         'type'    =>        'text',        // text is default if  "type" is not present
  6.         'label'    =>        'LabelText'    // the text for the label
  7.     ));
Here is a list of all possibile parameters that can be passed to the addElement() method as array keys for the "$params" parameter:
  1. name(mandatory)
  2. type
  3. label
  4. attributes
  5. labelOptions
  6. parentEl
  7. events
  8. validate
  9. values
  10. value
Some of these parameters can be added to field values like select, radio and checkbox groups, with "[brackets]". Ex: attributes[]. See USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for detailed usage.

The following paragraphs, 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:

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

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 _elAttributes property. New attributes can be added with the addElAttribute() and 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 _elAttributes property. New attributes can be added with the addElAttribute() and addElAttributes() methods, see Extending the compiler with custom attributes.

See Adding attributes to label container for examples and detailed usage.

Type: array


parentEl

Adds html attributes to the parent container of the field, 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.

See Adding attributes to field container for examples and detailed usage.

Type: array


events

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

the following field types are supported:

  1. text
  2. password
  3. textarea
  4. submit
  5. select
  6. radio
  7. checkbox
  8. checkboxgroup (will be added to all values)
  9. radiogroup (will be added to all values)
See ADDING FIELD EVENTS for detailed usage.

Type: array


validate

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

the following field types are supported:

  1. text
  2. password
  3. textarea
  4. submit
  5. select
  6. radio
  7. checkbox
  8. checkboxgroup (will be added to all values)
  9. radiogroup (will be added to all values)

see Adding Fields To The Validator for example usage.

Type: array|string


values

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

  1. select
  2. radiogroup
  3. checkboxgroup
  4. composite
  5. fieldset
See Adding values as an array (select,radiogroup,checkboxgroup) for examples to add values for select,radiogroup and checkboxgroup.

See Adding fields as an array of values (composite,fieldset) for examples 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 fields:

  1. text
  2. radio
  3. checkbox
  4. textarea
  5. password
  6. submit
  7. custom (any html code can be passed as value)
See Adding values as a string for example usage.

Type: string


ADDING FIELDS EXAMPLES

The 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 for all possibile parameters.

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

Adding a Text Field

  1. // addding a text field
  2.     $form->addElement(array
  3.     (    
  4.         'name'    =>        'fieldName',    // mandatory, will throw a warning if not present
  5.         'type'    =>        'text',        // text is default if  "type" is not present
  6.         'label'    =>        'LabelText'    // the text for the label
  7.     ));
The following fields can be created like shown in the example above as they do not require a "value":
  1. text
  2. radio
  3. checkbox
  4. textarea
  5. password
  6. submit
The following fields require a "value", or the class will throw a warning:
  1. select
  2. radiogroup
  3. checkboxgroup
  4. composite
  5. fieldset
  6. custom


Adding a Select Field

  1. // adding a select field
  2.     $values=array(''=>'Choose','enquiry'=>'Enquiry','information'=>'Information',
  3.                                         'billing'=>'Billing','other'=>'Other');
  4.     $form->addElement(array
  5.     (    
  6.         'name'    =>        'fieldName1',
  7.         'type'    =>        'select',        
  8.         'label'    =>        'LabelText',
  9.         'values'    =>        $values // adding previously created array with values
  10.     ));
To make an option selected you can use "[brackets]", see USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES.


Adding a Checkboxgroup

  1. // adding a checkboxgroup
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'checkboxgroup',
  5.         'name'            =>        'fieldName5',
  6.         'values'            =>        array('yes'=>'Yes !!! (please)','no'=>'No (thank you)'),
  7.         'attributes'        =>        array('cols'=>2// display values inline
  8.     ));
the "cols" attribute controls how many columns the group will have. The default value is 1.

To make a checkbox checked you can use "[brackets]", see USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES.


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.

  1. // adding a composite field for previously created fields
  2.     $form->addElement(array
  3.     (    
  4.         'name'    =>        'fieldName2',
  5.         'type'    =>        'composite',        
  6.         'values'    =>        array('fieldName','fieldName1'// previously created field names
  7.     ));
The following fields can be added like shown in the example above: fieldset, composite.

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


Adding a Custom Field

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" for this field type.

  1. // adding a spacer
  2.     $form->addElement(array
  3.     (
  4.         'type'    =>        'custom',
  5.         'name'    =>        'spacer1',
  6.         'value'    =>        $form->addSpacer('3px')
  7.     ));
The custom field type will only accept the following parameters:
  1. name
  2. type
  3. 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 _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','align','events',
  3.                         'title','selected','cols','rows','equalTo','border','pattern','cellpadding','cellspacing');

Adding attributes to fields

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

  1. // adding a textarea field
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'textarea',
  5.         'name'            =>        'fieldName8',
  6.         'label'            =>        'labelText',
  7.         // adding html attributes to the textarea, set style=>false to remove default styles for 1 field
  8.         'attributes'        =>        array('id'=>'fieldID','class'=>'some-class','style'=>false)
  9.     ));
To add attributes to values for select and raidio/checkbox groups we can use "[brackets]" like shown in the next example:
  1. // adding a select field
  2.     $values=array(''=>'Choose','enquiry'=>'Enquiry','information'=>'Information',
  3.                                         'billing'=>'Billing','other'=>'Other');
  4.     $form->addElement(array
  5.     (    
  6.         'name'                =>        'fieldName10',
  7.         'type'                =>        'select',        
  8.         'label'                =>        'LabelText',
  9.         'values'                =>        $values,
  10.         'attributes[]'            =>        array('class'=>'someClass')// will add the class to all select options
  11.         'attributes[enquiry]'        =>        array('selected'=>1// making 1 option selected
  12.     ));
See USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for more details.


Adding attributes to label container

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

  1. // adding a textarea field
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'textarea',
  5.         'name'            =>        'fieldName11',
  6.         'label'            =>        'labelText',
  7.         // setting a different style and changing alignment for a label container
  8.         'labelOptions'        =>        array('align'=>'top','style'=>'margin:10px')
  9.     ));
To add attributes to label containers of the field values for radio/checkbox groups we can use "[brackets]" like shown in the next example:
  1. // adding a radiogroup
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'radiogroup',
  5.         'name'            =>        'fieldName12',
  6.         'values'            =>        array('yes'=>'Yes !!! (please)','no'=>'No (thank you)'),
  7.         'labelOptions'        =>        array('style'=>false)// removing default style for label container of the field
  8.         'labelOptions[]'    =>        array('align'=>'top')// aligning labels of all values to the top 
  9.         'labelOptions[yes]'    =>        array('class'=>'some-class'// adding a class to the label container of 1 value
  10.     ));
See USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for more details.


Adding attributes to field container

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

  1. // adding a submit button
  2.     $form->addElement(array
  3.     (
  4.         'type'        =>    'submit',
  5.         'name'        =>    'fieldName13',
  6.         'value'        =>    'Submit',    // adding a value to the field
  7.         'parentEl'        =>    array('style'=>'text-align:right;'// adding style to the parent container
  8.     ));
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:
  1. // adding a checkboxgroup
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'checkboxgroup',
  5.         'name'            =>        'fieldName14',
  6.         'values'            =>        array('yes'=>'Yes !!! (please)','no'=>'No (thank you)'),
  7.         'parentEl[]'        =>        array('class'=>'some-class')// adding a class to the parent container of all values
  8.         'parentEl[yes]'        =>        array('id'=>'someID'// adding an id to the parent container of 1 value        
  9.     ));
See USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for more details.


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.     $form->AddElAttributes('default-value');
  3.     // adding an array of attributes
  4.     $form->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.     $form->setInputStyle(array('margin'=>'0 10px 0 0','vertical-align'=>false),'radio');
  3.     // changing the default styles for input fields
  4.     $form->setInputStyle(array('padding'=>'3px','border'=>'none'),'input');
The default 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'),//padding:2px;
  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.     $form->setLabelStyle(array('float'=>false,'color'=>'red'),1);
  3.     // changing the default styles for the label container for radios and checkboxes 
  4.     $form->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.     $form->setLabelStyle(array('padding'=>'3px','border'=>'none'),3,'right');
The default 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 templates 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.     $form->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.     $form->customTpl(array('spacer'=>'<div style="clear:both;height:{spacerVal}" {id}><hr style="width:'.$width.';"></div>'));
The default templates for all html elements are stored in the $_htmlTpls property.
  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 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:

  1. text
  2. radio
  3. checkbox
  4. textarea
  5. password
  6. submit
  7. custom (any html code can be passed as value)
This is how we can add a value to a field as a string:
  1. // adding a submit button
  2.     $form->addElement(array
  3.     (
  4.         'type'        =>    'submit',
  5.         'name'        =>    'fieldName3',
  6.         'value'        =>    'Submit'    // adding a value to the field
  7.     ));
The same result can be achieved with the "attributes" parameter.
  1. // adding a submit button
  2.     $form->addElement(array
  3.     (
  4.         'type'        =>    'submit',
  5.         'name'        =>    'fieldName4',
  6.         'attributes'    =>    array('value'=>'Submit')    // same as the "value" parameter
  7.     ));


Adding values as an array (select,radiogroup,checkboxgroup)

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

  1. select
  2. radiogroup
  3. checkboxgroup
The following examples demonstrate how values can be added as an array, with values as array keys and labels as array values:
  1. // adding a select field
  2.     $values=array(''=>'Choose','enquiry'=>'Enquiry','information'=>'Information',
  3.                                         'billing'=>'Billing','other'=>'Other');
  4.     $form->addElement(array
  5.     (    
  6.         'name'    =>        'fieldName1',
  7.         'type'    =>        'select',        
  8.         'label'    =>        'LabelText',
  9.         'values'    =>        $values // adding previously created array with values
  10.     ));
To add parameters to values "[brackets]" can be used, see USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for more details.


Adding fields as an 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:

  1. fieldset
  2. composite
The following examples demostrate how values can be added as an array with the names of the previously created fields as values.
  1. // adding a composite field for previously created fields
  2.     $form->addElement(array
  3.     (    
  4.         'name'    =>        'fieldName2',
  5.         'type'    =>        'composite',        
  6.         'values'    =>        array('fieldName','fieldName1'// previously created field names
  7.     ));
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.

  1. select
  2. radiogroup
  3. checkboxgroup
the select input only accepts brackets for the "attributes" parameter.
  1. // adding a select field
  2.     $values=array(''=>'Choose','enquiry'=>'Enquiry','information'=>'Information',
  3.                                         'billing'=>'Billing','other'=>'Other');
  4.     $form->addElement(array
  5.     (    
  6.         'name'            =>        'fieldName6',
  7.         'type'            =>        'select',        
  8.         'label'            =>        'LabelText',
  9.         'values'            =>        $values,
  10.         'attributes[]'        =>        array('class'=>'someClass')    // will add the class to all select options
  11.     ));
Radio/checkbox groups accept the following parameters with "[brackets]":
  1. attributes
  2. labelOptions
  3. parentEl
  4. events (if field name is specified)
  5. validate (if field name is specified)
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:
  1. // adding a radiogroup
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'radiogroup',
  5.         'name'            =>        'fieldName7',
  6.         'values'            =>        array('yes'=>'Yes !!! (please)','no'=>'No (thank you)'),
  7.         'labelOptions[]'    =>        array('align'=>'top')// aligning labels of all values to the top
  8.         'attributes[yes]'    =>        array('checked'=>1)// making 1 value checked
  9.     ));
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 FIELD EVENTS

The "events" parameter is used to attach javascript events to form fields.

  1. // adding a submit button
  2.     $form->addElement(array
  3.     (
  4.         'type'        =>    'submit',
  5.         'name'        =>    'fieldName15',
  6.         'events'        =>    array('onClick'=>'return false;'// attaching js events to the field
  7.     ));
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:

  1. // adding a checkboxgroup
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'checkboxgroup',
  5.         'name'            =>        'fieldName16',
  6.         'values'            =>        array('yes'=>'Yes !!! (please)','no'=>'No (thank you)'),
  7.         'events[yes]'        =>        array('onClick'=>'return false;'// attaching js events to 1 field value        
  8.     ));
See USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for more details.

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.     $form->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.     $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.
  1. // initialize the class, but don't print the form
  2.     require_once('PtcForms.php');
  3.     $form=new PtcForms(array("print_form"=>false));
  1. // storing the form inside a $var with "print_form" option set to false
  2.     $var=$form->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 validate property 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 _elAttributes property..

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
  1. // addding a password field
  2.     $form->addElement(array
  3.     (    
  4.         'name'    =>        'passwdField',
  5.         'type'    =>        'password',
  6.         'label'    =>        'LabelText',
  7.         'validate'    =>        'required' // adding required for this field
  8.     ));
  9.     
  10.     // addding 1 more password field
  11.     $form->addElement(array
  12.     (    
  13.         'name'    =>        'passwdField1',
  14.         'type'    =>        'password',
  15.         'label'    =>        'LabelText',
  16.         'validate'    =>        array('required','equalTo'=>'passwdField'// adding multiple validators for this field
  17.     ));
Any other value will be interpreted as a custom function.
  1. // some custom function that will be added to the validator(taken from ptcforms-ex1.php)
  2.     function some_func()
  3.     {
  4.         // do something with $_POST or $_GET arrays and return true or false
  5.     }
  6.     
  7.     // adding a text field
  8.     $form->addElement(array
  9.     (    
  10.         'name'    =>        'fieldName17',
  11.         'type'    =>        'text',
  12.         'label'    =>        'LabelText',
  13.         'validate'    =>        'some_func'
  14.     ));
Radio/checkbox groups will add validation to all field values, to add validation to 1 value for radio/checkboxgroup use "[brackets]":
  1. // adding a checkboxgroup
  2.     $form->addElement(array
  3.     (
  4.         'type'            =>        'checkboxgroup',
  5.         'name'            =>        'fieldName16',
  6.         'values'            =>        array('yes'=>'Yes !!! (please)','no'=>'No (thank you)'),
  7.         'validate[yes]'        =>        'required' // adding validation to 1 checkbox only        
  8.     ));
See USING [BRACKETS] TO ADD PARAMETERS TO FIELD VALUES for more details.


Validating The Form (Server Side)

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

  1. // adding a submit button
  2.     $form->addElement(array
  3.     (    
  4.         'name'    =>        'lg_login',
  5.         'type'    =>        'submit',
  6.         'value'    =>        'Login'
  7.     ));
  8.     
  9.     $err_msg='';
  10.     if(@$_POST['lg_login'])    // check if the form was sent
  11.     {
  12.         /* VALIDATE THE FORM SERVER SIDE */
  13.         $validate=$form->validate();    
  14.         if(!$validate['isValid'])            // returns a bool(true/false)
  15.         {
  16.             $err_msg='<div class="errMsg" style="text-align:center;width:'.$options['form_width'].'">
  17.                                                         Wrong user ID or password!</div><br>';
  18.         }
  19.  
  20.     }
For the validator to work, remember to always call 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 following methods against the $_POST or $_GET arrays:
  1. validateEmail()
  2. validateEqualTo()
  3. validateNumber()
  4. validatePattern()
  5. validateRequired()
This example will try to demonstrate the possibility of using these methods separately:
  1. $err_msg='';
  2.     if(@$_POST['lg_login'])    // check if the form was sent
  3.     {
  4.         
  5.         if(!$form->validateNumber('someFieldName',$_POST))    // check if value is numeric
  6.         {
  7.             // form is not valid
  8.         }
  9.         else if(!$form->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 Fri, 30 Aug 2013 15:28:55 +0200 by phpDocumentor 1.4.3