Overview

To build and display your form you'll have to include 4 php code blocks :

  1. First block at the very beginning of your page to include Form.php and build the form.
  2. Second block in your <head></head> section to call required css files for plugins.
  3. Third block in <body></body> section to render your form.
  4. Fourth block just before </body> to call required js files and js code to activate plugins.

Here is an example of page containing a form :

<?php

    // set namespace
    use phpformbuilder\Form;

    // start session
    session_start();

    // include Form.php
    include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/Form.php';

    // instanciate form and add fields
    $form = new Form('my-form', 'horizontal', 'novalidate', 'material');
    $form->addInput('text', 'user-name', 'Your Name', 'name', 'required=required');
    [...]
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>My form</title>

        <!-- Bootstrap CSS -->
        <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
        <?php

            // call css files for plugins
            $form->printIncludes('css');
        ?>
    </head>
    <body>
        <h1 class="text-center">My form</h1>
        <div class="container">
        <div class="row">
                <div class="col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <?php

                // render the form
                $form->render();
                ?>
                </div>
            </div>
        </div>
        <!-- jQuery -->
        <script src="//code.jquery.com/jquery.js"></script>
        <!-- Bootstrap JavaScript -->
        <script src="../assets/js/bootstrap.min.js"></script>
        <?php

            // call required js files and js code to activate plugins
            $form->printIncludes('js');
            $form->printJsCode();
        ?>
    </body>
    </html>

                        

Themes

Bootstrap 3

Default'theme is Bootstrap 3.

All options are ready to use, and will generate all Bootstrap's markup and classes.

Material Design

Material Design forms are based on Bootstrap 3.

Markup and options are the same for both.

To create a Material Design form, set framework to material :

$form = new Form('my-form', 'horizontal', 'novalidate', 'material');

More details about __construct here : Main functions > General > Construct

Options

Overview

Options are defining HTML wrappers and classes.
Default options are Bootstrap 3's.
Material Design Theme uses same markup as Bootstrap, and is activated with bootstrap-material-design included plugin called by __construct() function.
Each can be overwritten the way you want to match other framework

For example, with Bootstrap, each group (label + element) has to be wrapped into a <div class="form-group"></div> and to have a .form-control class

We also need do add .col-sm-x & .control-label to labels,
and to wrap elements with <div class="col-sm-x"></div>.

All will be easily done with Form options.

if needeed, wrappers can contain 2 html elements.
This can be done with elementsWrapper, checkboxWrapper and radioWrapper.

To add input wrapper, see addInputWrapper function.

Default options (Bootstrap 3's)

$options = array(
    'formInlineClass'          => 'form-inline',
    'formHorizontalClass'      => 'form-horizontal',
    'formVerticalClass'        => '',
    'elementsWrapper'          => '<div class="form-group"></div>',
    'checkboxWrapper'          => '<div class="checkbox"></div>',
    'radioWrapper'             => '<div class="radio"></div>',
    'wrapElementsIntoLabels'   => false,
    'wrapCheckboxesIntoLabels' => true,
    'wrapRadiobtnsIntoLabels'  => true,
    'elementsClass'            => 'form-control',
    'wrapperErrorClass'        => 'has-error',
    'elementsErrorClass'       => '',
    'textErrorClass'           => 'text-danger',
    'horizontalLabelClass'     => 'control-label',
    'horizontalLabelCol'       => 'col-sm-4',
    'horizontalOffsetCol'      => 'col-sm-offset-4',
    'horizontalElementCol'     => 'col-sm-8',
    'inlineCheckboxLabelClass' => 'checkbox-inline',
    'inlineRadioLabelClass'    => 'radio-inline',
    'btnGroupClass'            => 'btn-group',
    'requiredMark'             => '<sup class="text-danger">* </sup>',
    'openDomReady'             => '$(document).ready(function () {',
    'closeDomReady'            => '});'
);

Example of HTML code generated for each option
formInlineClass <form class="form-inline" [...]>
formHorizontalClass <form class="form-horizontal" [...]>
formVerticalClass <form class="form-vertical" [...]>
elementsWrapper <div class="form-group">
[<label> ... </label>]
[<input>]
</div>
checkboxWrapper <div class="checkbox">
[<label>]
[<input type="checkbox">[text]]
[</label>]
</div>
radioWrapper <div class="radio">
[<label>]
[<input type="radio">]
[</label>]
</div>
wrapElementsIntoLabels (if set to true) <label>[input | textarea | ...]</label>
wrapCheckboxesIntoLabels (if set to true) <label>[checkbox]</label>
wrapRadiobtnsIntoLabels (if set to true) <label>[radio]</label>
elementsClass <input class="form-control" [...]>
wrapperErrorClass <div class="[form-group] has-error">
elementsErrorClass <input class="[form-control] error-class" [...]>
textErrorClass <p class="text-danger"> ... </p>
horizontalLabelClass*,
horizontalLabelCol*
<label class="col-sm-4 control-label">...</label>
horizontalOffsetCol* // when label is empty, automaticaly offsetting field container
<div class="col-sm-offset-4 [col-sm-8]">
[<input>]
</div>
horizontalElementCol* <div class="col-sm-8">
[<input>]
</div>
inlineRadioLabelClass <label class="radio-inline">...</label>
btnGroupClass <div class="btn-group">...</div>
inlineCheckboxLabelClass <label class="checkbox-inline">...</label>
requiredMark // required markup is automaticaly added on required fields
<label>my required text<sup class="text-danger"> *</sup></label>
openDomReady
(if not using jQuery,
changes the code your plugins
will be wrapped in)
$(document).ready(function() {
closeDomReady });

* appied only in horizontal forms

Customizing for other framework

For many other frameworks like Kube or Skeleton, you don't need all these wrappers and classes, but eventualy have to wrap elements with labels (Default form config is to put elements after labels like Bootstrap does).

You can do that easily, for example (Kube config) :

$kube_custom_options = array(
    'formInlineClass'          => '',
    'formHorizontalClass'      => 'forms', // default layout
    'formVerticalClass'        => '',
    'elementsWrapper'          => '<p></p>',
    'checkboxWrapper'          => '<div class="forms-inline-list"></div>',
    'radioWrapper'             => '<div class="forms-inline-list"></div>',
    'wrapElementsIntoLabels'   => true,
    'elementsClass'            => '',
    'wrapperErrorClass'        => '',
    'elementsErrorClass'       => 'input-error',
    'textErrorClass'           => 'error',
    'horizontalLabelClass'     => '',
    'horizontalLabelCol'       => '',
    'horizontalOffsetCol'      => '',
    'horizontalElementCol'     => '',
    'inlineCheckboxLabelClass' => '',
    'inlineRadioLabelClass'    => '',
    'requiredMark'             => '<span class="req">*</span>',
    'openDomReady'             => '$(document).ready(function() {',
    'closeDomReady'            => '});'
    );
    $form->setOptions($kube_custom_options);
    

If you always use the same framework, maybe the best way is to change default config in form class.

Main functions

General

construct

$form = new Form($form_ID, $layout = 'horizontal', $attr = '', $framework = 'bs3');

    /**
     * Defines the layout (horizontal | vertical | inline).
     * Default is 'horizontal'
     * Clears values from session if self::clear has been called before
     * Catches posted errors
     * Adds hidden field with form ID
     * Sets elements wrappers
     *
     * @param string $form_ID       The ID of the form
     * @param string $layout        (Optional) Can be 'horizontal', 'vertical' or 'inline'
     * @param string $attr          (Optional) Can be any HTML input attribute or js event EXCEPT class
     *                              (class is defined in layout param).
     *                              attributes must be listed separated with commas.
     *                              Example : novalidate,onclick=alert(\'clicked\');
     * @param string $framework     (Optional) bs3 | material (Bootstrap 3 or Material design)
     */
 

options

Call setOptions only if you change defaults options

Go to Options for more details

$form->setOptions($options);

    /**
    * Sets form layout options to match your framework
    * @param array $user_options (Optional) An associative array containing the
    *                            options names as keys and values as data.
    */
    

Method

Default method is POST.

Call setMethod only if you change default method

$form->setMethod($method);

    /**
     * set sending method
     * @param string $method POST|GET
     */
 

Action

Default action is htmlspecialchars($_SERVER["PHP_SELF"])
(as recommended on http://www.w3schools.com/php/php_form_validation.asp).

Call setAction only if you change default action

$form->setAction($url, [$add_get_vars = true]);

    /**
    * Redefines form action
    *
    * @param boolean $add_get_vars (Optional) if $add_get_vars is set to false,
    *                              url vars will be removed from destination page.
    *                              Example : www.myUrl.php?var=value => www.myUrl.php
    */
    

Start Fieldset

Start your fieldset with optional legend.
Don't forget to call endFieldset to end your fieldset.

You can add several fieldsets on the same form.

$form->startFieldset('legend');

    /**
    * Starts a fieldset tag.
    * @param string $legend (Optional) Legend of the fieldset.
    */
    

End Fieldset

$form->endFieldset();

    /**
    * Ends a fieldset tag.
    */
    

startDependantFields

Start a dependant fields block.
dependant fields block is hidden and will be shown if $parent_field changes to one of $show_values. Don't forget to call endDependantFields to end your Dependant Fields block.

Each Dependant fields block can include one or several dependant fields blocks.

$form->startDependantFields($parent_field, $show_values);

    /**
     * Start a hidden block
     * which can contain any element and html
     * Hiden block will be shown on $parent_field change
     * if $parent_field value matches one of $show_values
     * @param  string $parent_field name of the field which will trigger show/hide
     * @param  string $show_values  single value or space separated values which will trigger show.
     * @return void
     */
 
Examples
   // dependant field with select
    $form->addHtml('If other, please tell us more ... ', 'subject', 'after');
    $form->addOption('subject', '', 'Your request concerns ...');
    $form->addOption('subject', 'Support', 'Support');
    $form->addOption('subject', 'Sales', 'Sales');
    $form->addOption('subject', 'Other', 'Other');
    $form->addSelect('subject');
    $form->startDependantFields('subject', 'Other');

    // Will be shown if subject == 'other'
    $form->addInput('text', 'subject-other', '', '', 'placeholder=Please tell more about your request ...');
    $form->endDependantFields();

    // dependant field with radio buttons
    $form->addRadio('radio-parent', 'show dependant', 1);
    $form->addRadio('radio-parent', 'hide dependant', 0);
    $form->printRadioGroup('radio-parent', 'Click one');
    $form->startDependantFields('radio-parent', 1);

    // Will be shown if radio-parent == 1
    $form->addRadio('xxx', 'yes', 1);
    $form->addRadio('xxx', 'no', 0);
    $form->printRadioGroup('xxx', 'Second question');
    $form->endDependantFields();
    
If other, please tell us more ...

endDependantFields

$form->endDependantFields();

    /**
    * Ends Dependant Fields block.
    */
    

$attr argument

Several element functions use a $attr argument.

The $attr argument accepts any html attribute or javascript event.

Use comma separated values (see examples below).

Examples
    $form->addInput('text', 'name', '', 'Your name : ', 'id=my-id, placeholder=My Text, required=required');

    $form->addInput('password', 'pass', '', 'Your password : ', 'required=required, pattern=(.){7\,15}');

    $form->addTextarea('my-textarea', '', 'Your message : ', 'cols=30, rows=4');

    $form->addBtn('button', 'myBtnName', 1, 'Cancel', 'class=btn btn-danger, onclick=alert(\'cancelled\');');
    

Elements

Input

$form->addInput($type, $name [, $value = '', $label = '', $attr = '']);

    /**
    * Adds input to the form
    *
    * @param string $type Accepts all input html5 types except checkbox and radio :
    *                      button, color, date, datetime, datetime-local,
    *                      email, file, hidden, image, month, number, password,
    *                      range, reset, search, submit, tel, text, time, url, week
    * @param string $name The input name
    * @param string $value (Optional) The input default value
    * @param string $label (Optional) The input label
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    *                                attributes must be listed separated with commas.
    *                                If you don't specify any ID as attr, the ID will be the name of the input.
    *                                Example : class=my-class,placeholder=My Text,onclick=alert(\'clicked\');
    */
    

Input Groups

Input Groups allow to have several inputs / selects on the same line in horizontal forms.

Always create your input group BEFORE creating the input elements.

$form->groupInputs($input1, $input2 [, $input3 = '', $input4 = '']);

    /**
    * Allows to group inputs in the same wrapper
    * @param string $input1 The name of the first input of the group
    * @param string $input2 The name of the second input of the group
    * @param string $input3 [optional] The name of the third input of the group
    */
    
Input Groups Example
    $form->groupInputs('street', 'zip', 'countries');
    $form->setOptions(array('horizontalElementCol' => 'col-sm-3'));
    $form->addInput('text', 'street', '', 'Your adress : ', 'placeholder=street,required=required');
    $form->setOptions(array('horizontalLabelCol' => '', 'horizontalOffsetCol' => '', 'horizontalElementCol' => 'col-sm-2'));
    $form->addInput('text', 'zip', '', '', 'placeholder=zip code,required=required');
    $form->setOptions(array('horizontalElementCol' => 'col-sm-3'));
    $form->addOption('countries', '', 'Countries');
    $form->addOption('countries', 'United States', 'United States');
    $form->addOption('countries', 'Canada', 'Canada');
    $form->addOption('countries', 'France', 'France');
    $form->addSelect('countries', '', '');
    $form->setOptions(array('horizontalLabelCol' => 'col-sm-4', 'horizontalOffsetCol' => 'col-sm-4', 'horizontalElementCol' => 'col-sm-8')); // revert to default options

Textarea

$form->addTextarea($name, $value [, $label, $attr]);

    /**
    * Adds textarea to the form
    * @param string $name The textarea name
    * @param string $value (Optional) The textarea default value
    * @param string $label (Optional) The textarea label
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    *                                attributes must be listed separated with commas.
    *                                If you don't specify any ID as attr, the ID will be the name of the textarea.
    *                                Example : cols=30, rows=4;.
    */
    

Options for Select list

Always add your options BEFORE creating the select element

  1. Add your options
  2. Create your select
$form->addOption($selectName, $value, $txt [, $group_name, $attr]);

    /**
    * Adds option to the $select_name element
    *
    * @param string $select_name The name of the select element
    * @param string $value The option value
    * @param string $txt The text that will be displayed
    * @param string $group_name (Optional) the optgroup name
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    *                                attributes must be listed separated with commas.
    *                                If you don't specify any ID as attr, the ID will be the name of the option.
    *                                Example : class=my-class
    */
    

Select list

$form->addSelect($selectName, $label [, $attr = '', $displayGroupLabels = true]);

addSelect function plays nice with bootstrap-select plugin.
Just add 'selectpicker' class, data-attrs and phpformbuilder will do the job. (See example).

Don't forget to call $form->printIncludes('css'); and $form->printIncludes('js'); to add the required css/js files to your page.


    /**
    * Adds a select element
    *
    * IMPORTANT : Always add your options BEFORE creating the select element
    *
    * @param string $select_name The name of the select element
    * @param string $label (Optional) The select label
    * @param string $attr (Optional)  Can be any HTML input attribute or js event.
    *                                 attributes must be listed separated with commas.
    *                                 If you don't specify any ID as attr, the ID will be the name of the input.
    *                                 Example : class=my-class
    * @param string $displayGroupLabels (Optional) True or false.
    *                                              Default is true.
    */
    
Example with optgroup
    $form->addOption('select-with-groupnames', 'option-1', 'option 1', 'group 1');
    $form->addOption('select-with-groupnames', 'option-2', 'option 2', 'group 1', 'selected=selected');
    $form->addOption('select-with-groupnames', 'option-3', 'option 3', 'group 1');
    $form->addOption('select-with-groupnames', 'option-4', 'option 4', 'group 2');
    $form->addOption('select-with-groupnames', 'option-5', 'option 5', 'group 2');
    $form->addSelect('select-with-groupnames', 'Select please : ', '');
Example with multiple selections
for ($i=1; $i < 11; $i++) {
    $form->addOption('myMultipleSelectName[]', $i, 'option ' . $i);
}
$form->addSelect('myMultipleSelectName[]', 'Select please :
(multiple selections)', 'multiple=multiple');
Bootstrap-select plugin Example
    $form->addHtml('<span class="help-block">2 Arrows max.</span>', 'bootstrap-select-select[]', 'after');
    $form->addOption('bootstrap-select-select[]', 'arrow-left', 'arrow left', 'Arrows', 'data-icon=glyphicon-arrow-left');
    $form->addOption('bootstrap-select-select[]', 'arrow-right', 'arrow right', 'Arrows', 'data-icon=glyphicon-arrow-right');
    $form->addOption('bootstrap-select-select[]', 'arrow-down', 'arrow down', 'Arrows', 'data-icon=glyphicon-arrow-down');
    $form->addOption('bootstrap-select-select[]', 'arrow-up', 'arrow up', 'Arrows', 'data-icon=glyphicon-arrow-up');
    $form->addOption('bootstrap-select-select[]', 'circle-arrow-left', 'circle arrow left', 'Circle Arrows', 'data-icon=glyphicon-circle-arrow-left');
    $form->addOption('bootstrap-select-select[]', 'circle-arrow-right', 'circle arrow right', 'Circle Arrows', 'data-icon=glyphicon-circle-arrow-right');
    $form->addOption('bootstrap-select-select[]', 'circle-arrow-down', 'circle arrow down', 'Circle Arrows', 'data-icon=glyphicon-circle-arrow-down');
    $form->addOption('bootstrap-select-select[]', 'circle-arrow-up', 'circle arrow up', 'Circle Arrows', 'data-icon=glyphicon-circle-arrow-up');
    $form->addSelect('bootstrap-select-select[]', 'Choose : ', 'class=selectpicker, data-live-search=true, multiple=multiple, data-max-options=2, required=required');
2 Arrows max.

Country Select list

Always add your options BEFORE creating the select element

Country Select uses the bootstrap-select plugin, which requires Bootstrap's dropdown in your bootstrap.min.js

$form->addCountrySelect($select_name [, $label = '', $attr = '', $user_options = array()]);

    /**
    * adds a country select list with flags
    * @param array  $select_name
    * @param string $label        (Optional) The select label
    * @param string $attr         (Optional)  Can be any HTML input attribute or js event.
    *                             attributes must be listed separated with commas.
    *                             If you don't specify any ID as attr, the ID will be the name of the input.
    *                             Example : class=my-class
    * @param array  $user_options (Optional) :
    *                             lang            : MUST correspond to one subfolder of [PLUGINS_DIR]countries/country-list/country/cldr/
    *                             *** for example 'en', or 'fr_FR'              Default : 'en'
    *                             flags           : true or false.              Default : true
    *                             *** displays flags into option list
    *                             flag_size       : 16 or 32                    Default : 32
    *                             return_value    : 'name' or 'code'            Default : 'name'
    *                             *** type of the value that will be returned
    *                             show_tick       : true or false
    *                             *** shows a checkmark beside selected options Default : true
    *                             live_search     : true or false               Default : true
    */
    
Country select Example
if(!isset($_SESSION['your-form-id']['country'])) {
    $_SESSION['your-form-id']['country'] = 'United Kingdom'; // default country value
}
$form->addCountrySelect('country', 'country : ');

Radio Btns

  1. Add your radio buttons
  2. Call printRadioGroup
$form->addRadio($group_name, $label, $value [, $attr = '']);

    /**
    * Adds radio button to $group_name element
    *
    * @param string $group_name The radio button groupname
    * @param string $label The radio button label
    * @param string $value The radio button value
    * @param string $attr  (Optional) Can be any HTML input attribute or js event.
    *                      attributes must be listed separated with commas.
    *                      Example : checked=checked
    */
    

Print Radio Group

$form->printRadioGroup($group_name, $label [, $inline = true, $attr = '']);

    /**
    * Prints radio buttons group.
    *
    * @param string $group_name The radio button group name
    * @param string $label (Optional) The radio buttons group label
    * @param string $inline (Optional) True or false.
    *                                  Default is true.
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    *                       attributes must be listed separated with commas.
    *                       If you don't specify any ID as attr, the ID will be the name of the input.
    *                       Example : class=my-class
    */
    
Example
    $form->addRadio('myRadioBtnGroup', 'choice one', 'value 1');
    $form->addRadio('myRadioBtnGroup', 'choice two', 'value 2', 'checked=checked');
    $form->addRadio('myRadioBtnGroup', 'choice three', 'value 3');
    $form->printRadioGroup('myRadioBtnGroup', 'Choose one please', true, 'required=required');

Checkboxes

  1. Add your checkboxes
  2. Call printCheckboxGroup
$form->addCheckbox($group_name, $label, $value [, $attr = '']);

    /**
    * Adds checkbox to $group_name
    *
    * @param string $group_name The checkbox groupname (will be converted to an array of indexed value)
    * @param string $label The checkbox label
    * @param string $value The checkbox value
    * @param string $attr  (Optional) Can be any HTML input attribute or js event.
    *                      attributes must be listed separated with commas.
    *                      Example : checked=checked
    */
    

Print Checkbox Group

$form->printCheckboxGroup($group_name, $label [, $inline = true, $attr = '']);

    /**
    * Prints checkbox group.
    *
    * @param string $var (Optional) description
    *
    * @param string $group_name The checkbox button group name
    * @param string $label (Optional) The checkbox group label
    * @param string $inline (Optional) True or false.
    *                                  Default is true.
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    *                       attributes must be listed separated with commas.
    *                       If you don't specify any ID as attr, the ID will be the name of the input.
    *                       Example : class=my-class
    */
    
Example
    $form->addCheckbox('myCheckboxGroup', 'choice one', 'value 1');
    $form->addCheckbox('myCheckboxGroup', 'choice two', 'value 2', 'checked=checked');
    $form->addCheckbox('myCheckboxGroup', 'choice three', 'value 3', 'checked=checked');
    $form->printCheckboxGroup('myCheckboxGroup', 'Check please : ', true, 'required=required');
    $form->render();
    

Buttons

For a single button, just call addBtn and let $btnGroupName empty.

For button group, call addBtn for each button, give a name to $btnGroupName, then call printBtnGroup

$form->addBtn($type, $name, $value, $text [, $attr = '', $btnGroupName = '']);

    /**
    * Adds button to the form
    *
    * If $btnGroupName is empty, the button will be automaticaly displayed.
    * Otherwise, you'll have to call printBtnGroup to display your btnGroup.
    *
    * @param string $type The html button type
    * @param string $name The button name
    * @param string $value The button value
    * @param string $text The button text
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    *                                 attributes must be listed separated with commas.
    *                                 If you don't specify any ID as attr, the ID will be the name of the input.
    *                                 Example : class=my-class,onclick=alert(\'clicked\');
    * @param string $btnGroupName (Optional) If you want to group several buttons, group them then call printBtnGroup.
    *
    */
    

Print Btn Group

$form->printBtnGroup($btnGroupName);

    /**
    * Prints buttons group.
    *
    * @param string $btnGroupName The buttons group name
    * @param string $label (Optional) The buttons group label
    *
    */
    
Single button example
$form->addBtn('submit', 'myBtnName', 1, 'Submit form', 'class=btn btn-primary');
Button group example
$form->addBtn('submit', 'mySubmitBtnName', 1, 'Submit form', 'class=btn btn-primary', 'myBtnGroup');
    $form->addBtn('button', 'myCancelBtnName', 0, 'Cancel', 'class=btn btn-danger, onclick=alert(\'cancelled\');', 'myBtnGroup');
    $form->printBtnGroup('myBtnGroup');

Set Cols

Set Cols wraps label and fields with Bootstrap columns.

(See example below)

$form->setCols($labelsCols, $fieldsCols [, $breakpoint = 'sm']);

    /**
    * Shortcut for
    * $options = array(
    *        'horizontalLabelCol'       => 'col-' . $breakpoint . '-' . $labelsCols,
    *        'horizontalOffsetCol'      => 'col-' . $breakpoint . '-offset-' . $labelsCols,
    *        'horizontalElementCol'     => 'col-' . $breakpoint . '-' . $fieldsCols,
    * );
    * $form->setOptions($options);
    *
    * @param number $labelsCols number of columns for label
    * @param number $fieldsCols number of columns for fields
    * @param string $breakpoint Bootstrap's breakpoints : xs | sm | md |lg
    *
    */
    
Example
$form->setCols(3, 9);
$form->addInput('text', 'username', '', 'Name');
Will generate the following markup :
<div class="form-group">
    <label for="username" class="col-sm-3 control-label">Name</label>
    <div class="col-sm-9">
        <input id="$name" name="$name" type="text" value=""  class="form-control">
    </div>
</div>
Equivalent to :
$options = array(
    'horizontalLabelCol'       => 'col-sm-3,
    'horizontalOffsetCol'      => 'col-sm-offset-3,
    'horizontalElementCol'     => 'col-sm-9
);
$form->setOptions($options);
$form->addInput('text', 'username', '', 'Name');

Add Icon

Adds an icon before or after the choosen field

$form->addIcon($input_name, $icon_html, $pos);
    /**
     * shortcut to prepend or append icon to an input
     * @param string $input_name the name of target input
     * @param string $icon_html  icon html code
     * @param string $pos        before | after
     */
Example
$form->addIcon('username', '<span class="glyphicon glyphicon-user"></span>', 'before');
$form->addInput('text', 'username', '', 'Name');

Custom HTML

You can add some html code at any place you want when creating your form.

This way, you can :

When your HTML is linked to an element, always call addHtml BEFORE creating the element

For details, see examples below

$form->addHtml($html [, $element_name = '', $pos = 'after']);

    /**
    * Adds HTML code at any place of the form
    *
    * @param string $html The html code to add.
    * @param string $element_name (Optional) If not empty, the html code will be inserted.
    *                                        just before or after the element.
    * @param string $pos (Optional) If $element_name is not empty, defines the position
    *                               of the inserted html code.
    *                               Values can be 'before' or 'after'.
    */
    
Add HTML between elements
$form->addInput('text', 'input-name', '', 'Enter your name : ');
$form->addHtml('<div class="alert alert-danger"><p>Your e-mail adress is required</p></div>');
$form->addInput('text', 'email', '', 'Enter your e-mail : ');

Your e-mail adress is required

Prepend or append HTML to elements
(requires also addInputWrapper)
$form->addInputWrapper('<div class="input-group"></div>', 'phone-input');
$form->addHtml('<div class="input-group-addon"><span class="glyphicon glyphicon-earphone"></span></div>', 'phone-input', 'before');
$form->addInput('text', 'phone-input', '', 'Your phone : ');
$form->addInputWrapper('<div class="input-group"></div>', 'email-input');
$form->addHtml('<div class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></div>', 'email-input', 'after');
$form->addInput('text', 'email-input', '', 'Your e-mail : ');

Custom html with input wrapper

wrapper can be one or two html elements

$form->addInputWrapper($html, $element_name);

    /**
    * Wraps the element with html code.
    *
    * @param string $html The html code to wrap the element with.
    *                     The html tag must be opened and closed.
    *                     Example : <div class="my-class"></div>
    * @param string $element_name The form element to wrap.
    */
    
Example
$form->addInputWrapper('<div class="row"><div class="col-lg-4"></div></div>', 'myInputLg4');
$form->addInput('text', 'myInputLg4', '', 'Input wrapped with col-lg-4 : ' );

Render

Renders the form.

Set $debug to true if you wants to display HTML code

Set $display to false if you wants to return HTML code but not display on page

$form->render([$debug = false, $display = true]);

    /**
     * Renders the html code of the form.
     *
     * @param boolean $debug   (Optional) True or false.
     *                         If true, the html code will be displayed
     * @param boolean $display (Optional) True or false.
     *                         If false, the html code will be returned but not displayed.
     *
     */
 

Print plugins includes

Call printIncludes to render html code to include css or js files needed by plugins

Allows you to call css/js files at the right places (generaly css inside your <head></head> section, and js just before </body>.

With cssargument, adds also a few lines to style grouped inputs (several inputs on same line) on small screens.

If your form contains no plugin, no need to call this function.

$form->printIncludes($type, $debug = false);

    /**
     * Prints html code to include css or js files needed by plugins.
     *
     * @param string  $type    value : 'css' or 'js'
     * @param boolean $debug   (Optional) True or false.
     *                         If true, the html code will be displayed
     * @param boolean $display (Optional) True or false.
     *                         If false, the html code will be returned but not displayed.
     *
     */
 
Example with colorpicker plugin
$form->addInput('text', 'my-colorpicker', '', 'ColorPicker : ');
$form->addPlugin('colorpicker', '#my-colorpicker');
$form->printIncludes('css');
<link href="../../phpformbuilder/plugins/colpick/css/colpick.css" rel="stylesheet" media="screen">

$form->addInput('text', 'my-colorpicker', '', 'ColorPicker : ');
$form->addPlugin('colorpicker', '#my-colorpicker');
$form->printIncludes('js');
<script src="../../phpformbuilder/plugins/colpick/js/colpick.js"></script>

Print plugins JS code

Prints the JS code generated by the plugin.

If your form contains no plugin, no need to call this function.

$form->printJsCode($debug = false);

    /**
     * Prints js code generated by plugins.
     * @param boolean $debug   (Optional) True or false.
     *                         If true, the html code will be displayed
     * @param boolean $display (Optional) True or false.
     *                         If false, the html code will be returned but not displayed.
     */
 
Example with colorpicker plugin
$form->addInput('text', 'my-colorpicker', '', 'ColorPicker : ');
$form->addPlugin('colorpicker', '#my-colorpicker');
$form->printJsCode();
<script type="text/javascript">
    $(document).ready(function() {
        $("#my-colorpicker").colpick({
            onSubmit:function(hsb,hex,rgb,el) {
                $(el).val('#'+hex);
                $(el).colpickHide();
            }
        });
    });
</script>

E-mail Sending

sendMail function

$sent_message = Form::sendMail($from_email, $adress, $subject, $filter_values);

See details at E-MAIL SENDING

sendAdvancedMail function

$sent_message = Form::sendAdvancedMail($options);

See details at E-MAIL SENDING

Registering / Clearing values

registerValues (static function)

When you instantiate a form, it will automatically store corresponding posted values in session unless you called clear function before creating your form.

Values are registered this way : $_SESSION['form-id']['field-name']

You can call Form::registerValues('form-id') manually at any time.

Form::registerValues('form-id');
    /**
    * register all posted values in session
    * @param string $form_ID
    *
    * ex : $_SESSION['form-id']['field-name'] = $_POST['field-name'];
    */

mergeValues (static function)

mergeValues is used to merge previously registered values in a single array.
Usefull for step forms to send all steps values by email or store into database for example.

Form::mergeValues(array('step-form-1', 'step-form-2', 'step-form-3'));
    /**
    * merge previously registered session vars => values of each registered form
    * @param  array $forms_array array of forms IDs to merge
    * @return array pairs of names => values
    *                           ex : $values[$field_name] = $value
    */

clear (static function)

Clears the corresponding previously registered values from session.

Form::clear('form-id');

Extending main class

Extending Php Form Builder allows to create a complete form or form parts using a single customized function.

Created form or parts can be validated the same way, using a single customized function.

Very useful if you want for example :

  • Create a complete contact form and use it on several projects
  • Create several similar fields in a single form
  • Create and reuse several fields in different forms

See live examples with code in Templates

See phpformbuilder/FormExtended.php code

Plugins

Overview

For any plugin, you'll allways have to follow these 4 steps :

  1. Call addPlugin function
  2. Then create the corresponding element (exept for fileupload)
  3. Call $form->printIncludes('css'); in your <head> section
  4. Call $form->printIncludes('js'); then $form->printJsCode(); just before </body>

Don't forget to configure plugins path in plugins-path.php.

Php Form Builder includes the folowing jQuery plugins :

Plugins are located in plugin/ dir.

Plugins config are respective XML files in plugins-config/ dir.

You can easily :

Activating a plugin

Just call the addPlugin function

If your form uses plugin(s), you have to call $form->printIncludes('css'); in your <head> section
And $form->printIncludes('js'); then $form->printJsCode(); just before </body>

Don't forget to configure plugins path in plugins-path.php.

For default config, simply use addPlugin($plugin_name, $selector)

To use custom config, you'll have to specify $js_content and eventualy $js_replacements. See Customizing Plugins.

The following plugins are used in a different way, see linked sections :

$form->addPlugin($plugin_name, $selector, [$js_content = 'default', $js_replacements = ''])
    /**
    * Adds a javascript plugin to the selected field(s)
    * @param string $plugin_name The name of the plugin,
    *                            must be the name of the xml file
    *                            in plugins-config dir
    *                            without extension.
    *                            Example : colorpicker
    * @param string $selector The jQuery style selector.
    *                         Examples : #colorpicker
    *                                    .colorpicker
    * @param string $js_content (Optional) The xml node where your plugin code is
    *                                      in plugins-config/[your-plugin.xml] file
    * @param array $js_replacements (Optional) An associative array containing
    *                                          the strings to search as keys
    *                                          and replacement values as data.
    *                                          Strings will be replaced with data
    *                                          in <js_code> xml node of your
    *                                          plugins-config/[your-plugin.xml] file.
    */

File Upload

To create a fileupload element, call addFileUpload with the folowing arguments :

$type :
The type of the input, usualy 'file'.
$name :
The input name
$value :
The input value (usualy leave empty)
$label :
The input label
$attr :
Can be any HTML input attribute or js event.
$fileUpload_config :
An associative array containing :
'xml' =>
The xml node where your plugin code is in
plugins-config/fileupload.xml
'uploader' =>
The php uploader file in
plugins/jQuery-File-Upload/server/php/ folder
'btn-text' =>
The text of the upload button
'max-number-of-files' =>
The max number of files to upload

Default values for $fileUpload_config are :

'xml' =>
'default'
'uploader' =>
'defaultFileUpload.php'
'btn-text' =>
'Select files...'
'max-number-of-files' =>
1

File Upload is supplied with two ready configs :

  • default (defaultFileUpload.php)
  • images (imageFileUpload.php)

You can configure destination folder, file restrictions, Thumbnails and images sizes in the
form/plugins/jQuery-File-Upload/server/php/[YourFileUploadHandler].php

$form->addFileUpload($type, $name, [$value = '', $label = '', $attr = '', $fileUpload_config = ''])
    /**
    * Creates an input with fileupload plugin.
    *
    * The fileupload plugin generates complete html, js and css code.
    * You'll just have to call printIncludes('css') and printIncludes('js')
    * where you wants to put your css/js codes (generaly in <head> and just before </body>).
    *
    * @param string $type The node of the plugins-config/fileupload.xml file where is your code.
    *                     For example : 'default' or 'images'
    * @param string $name The upload field name.
    *                     Use an array (ex : name[]) to allow multiple files upload
    * @param string $value (Optional) The input default value
    * @param string $label (Optional) The input label
    * @param string $attr (Optional) Can be any HTML input attribute or js event.
    * @param array $fileUpload_config (Optional) An associative array containing :
    *                                            'xml'                 => The xml node where your plugin code is
    *                                                                     in plugins-config/fileupload.xml,
    *                                            'uploader'            => The php uploader file in
    *                                                                     plugins/jQuery-File-Upload/server/php/ folder
    *                                            'btn-text'            => The text of the upload button,
    *                                            'max-number-of-files' => The max number of files to upload
    *
    */

Material Design plugin

To switch your form to Material Design theme, instanciate with material as 4th parameter :

$form = new Form('my-form', 'horizontal', 'novalidate=true', 'material');

Included plugins examples

Autocomplete - https://jqueryui.com/autocomplete/

Arguments & parameters :

'default' (3rd parameter)
'default' js config will use $complete_list to autocomplete.
$complete_list
$complete_list is an associative array with '%availableTags%' as single key, and terms for completion as value (see code below).
Autocomplete
$form->addInput('text', 'autocomplete-input-1', '', '', 'placeholder=Search ...');
$complete_list = ['%availableTags%' => '"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"'];
$form->addPlugin('autocomplete', '#search-input-1', 'default', $complete_list);

Autocomplete with ajax call

Arguments & parameters :

'remote' (3rd parameter)
'remote' js config will call a file with ajax to autocomplete.
$replacements
An associative array with :
  • '%remote%' => [url of your ajax file]
  • '%minLength%' => minimum number of characters filled to call ajax autocomplete
Autocomplete with ajax call
$form->addInput('text', 'autocomplete-input-2', '', '', 'placeholder=Search ...');
$form->addHtml('Type at lease 2 characters, search for first name');
$replacements = [
    '%remote%' => '../assets/search-form-autocomplete/complete.php',
    '%minLength%' => '2'
];
$form_2->addPlugin('autocomplete', '#search-input-2', 'remote', $replacements);
Type at lease 2 characters, search for first name

Captcha - http://keith-wood.name/realPerson.html

Captcha example
$form->addInput('text', 'captcha', '', 'Type the characters please :', 'size=15');
$form->addPlugin('captcha', '#captcha', 'default');

Colorpicker - http://colpick.com/plugin

Colorpicker example
$form->addInput('text', 'defaultColorPicker', '', 'ColorPicker : ');
$form->addPlugin('colorpicker', '#defaultColorPicker');

Datepicker - http://jqueryui.com/datepicker/

Datepicker example
$form->addInput('text', 'myDatePicker', '', 'DatePicker : ');
$form->addPlugin('datepicker', '#myDatePicker');

FileUpload - https://github.com/blueimp/jQuery-File-Upload

File Upload example (uploads 2 images maxi and creates 3 thumbnails for each)
$fileUpload_config = array(
    'xml'                 => 'images',
    'uploader'            => 'imageFileUpload.php',
    'btn-text'            => 'Browse ...',
    'max-number-of-files' => 2
);

$form->addFileUpload('file', 'files[]', '', 'FileUpload : ', 'id=myFileUpload', $fileUpload_config);

/* Put this line in <head> section */

$form->printIncludes('css');

/* Put the 2 following lines just before </body> */

$form->printIncludes('js');
$form->printJsCode();

See live examples with code in Templates

Icheck - http://fronteed.com/iCheck/

Arguments : Array()

'%theme%' :
theme from plugins/icheck/skins/
(flat, futurico, line, minimal, polaris, square)
'%color%' :
color from plugins/icheck/skins/[theme]/
(aero, blue, flat, green, grey, orange, pink, purple, red, yellow)
Icheck
$form->addPlugin('icheck', 'input', 'default', array('%theme%' => 'square', '%color%' => 'green'));
$form->addRadio('human-or-robot', 'I\'m a human', 1);
$form->addRadio('human-or-robot', 'I\'m a robot', 0);
$form->printRadioGroup('human-or-robot', 'Are you a human or a robot ?', false, 'required=required');

Materialize

To switch your form to Material Design theme, instanciate with material as 4th parameter :

$form = new Form('my-form', 'horizontal', 'novalidate=true', 'material');

See live examples with code in Templates

HTML :
    <a data-remodal-target="#modal-target" class="btn btn-primary">Contact Us</a>
PHP :
    $form->modal('#modal-target');

    /**
     * wrap form in a modal
     * @param string $modal_target : href attribute of the link to modal
     */

See live examples with code in Templates

Passfield - http://antelle.github.io/passfield/index.html

Passfield example
    $form->addPlugin('passfield', '#user-password', 'lower-upper-min6');
    $form->addHtml('<span class="help-block">password must contain lowercase + uppercase letters and be 6 characters long</span>', 'user-password', 'after');
    $form->addInput('password', 'user-password', '', 'password', 'required=required');

Pre-configured patterns :

  • default : password must contain lowercase letters + numbers and be 8 characters long
    pattern validation :
    $validator->hasLowercase()->hasNumber()->minLength(8)->validate('user-password');
  • lower-upper-min8 : password must contain lowercase + uppercase letters and be 8 characters long
    pattern validation :
    $validator->hasLowercase()->hasUppercase()->minLength(8)->validate('user-password');
  • lower-upper-number-min8 : password must contain lowercase + uppercase letters + numbers and be 8 characters long
    pattern validation :
    $validator->hasLowercase()->hasUppercase()->hasNumber()->minLength(8)->validate('user-password');
  • lower-upper-number-symbol-min8 : password must contain lowercase + uppercase letters + numbers + symbols and be 8 characters long
    pattern validation :
    $validator->hasLowercase()->hasUppercase()->hasNumber()->hasSymbol()->minLength(8)->validate('user-password');

You can easily add your own patterns into phpformbuilder/plugins-config/passfield.xml.
A pattern generator is available at http://antelle.github.io/passfield/demo.html

Pickadate

Pickadate example
$form->addInput('text', 'user-date', '', 'Date', 'required=required');
$form->addPlugin('pickadate', '#user-date');

Pickadate Material

Pickadate Material example
$form->addInput('text', 'user-date-material', '', 'Date', 'required=required');
$form->addPlugin('pickadate', '#user-date-material');

See live examples with code in Templates

Popover - https://github.com/sandywalker/webui-popover

HTML :
    <a href="#" id="popover-link" class="btn btn-primary">Contact Us</a>
PHP :

    // with optional options :
    $popover_options = array(
        'placement' => 'bottom',
        'width' =>  500,
        'height' =>  'auto',
        'closeable' => true,
        'animation' => 'pop',
        'backdrop' => false
    );
    $form->popover('#popover-link', $popover_options);

    // or with default options :
    $form->popover('#popover-link');

    /**
    * wrap form in a popover
    * @param string $popover_link the id of the link which triggers popover
    * @param array  $options      (Optional) An associative array containing
    *                             'placement' : auto,top,right,bottom,left,top-right,top-left,bottom-right,bottom-left,auto-top,auto-right,auto-bottom,auto-left,horizontal,vertical
    *                             'width' : 'auto' or number
    *                             'height' : 'auto' or number
    *                             'closeable' : display close button or not
    *                             'animation' : pop with animation,values: null, pop,fade
    *                             'backdrop' : if backdrop is set to true, popover will use backdrop on open
    */

See live examples with code in Templates

tinyMce - http://www.tinymce.com/

tinyMce example
$form->addTextarea('content', '', 'tinymce : ', 'cols=100, rows=20, class=tinyMce');
$form->addPlugin('tinymce', '#content');

TinyMce + Word / Character Count example

TinyMce + Word / Character Count example
$form->addTextarea('content-tinymce', '', 'tinymce : ', 'cols=100, rows=20, class=tinyMce');
$form->addPlugin('tinymce', '#content-tinymce', 'word_char_count', array('%maxAuthorized%' => 200));

Pre-built configs are :

default
words + characters count
word
word count only
character
character count only

Word / Character Count

Word / Character Count example
$form->addTextarea('message', '', 'Your message : ', 'cols=30, rows=4, required=required');
$form->addPlugin('word-character-count', '#message', 'default', array('%maxAuthorized%' => 100));

Pre-built configs are :

default
words + characters count
word
word count only
character
character count only

Customizing plugins

Each plugin has it's own XML configuration file in plugins-config directory.

The XML structure is allways the same :

<root>
    <default>
        <includes>
            <css>
                <file>../../phpformbuilder/plugins/[plugin dir]/[plugin].css</file>
            </css>
            <js>
                <file>../../phpformbuilder/plugins/[plugin dir]/[plugin].js</file>
            </js>
        </includes>
        <js_code>
        <![CDATA[
        $("%selector%").[function]();
        ]]>
        </js_code>
    </default>
</root>

The addPlugin function has 4 arguments : $plugin_name, $selector, $js_content and $js_replacements

$js_content indicates the XML node you targets. (default value : 'default').

$selector will replace "%selector%" in XML.

To customize your plugin :

  1. Copy the <default> node structure and give it a name
    (for example, replace '<default>' with '<custom>')
  2. if the <includes> node has no need to be modified, delete it from your structure :
    default's include node will be used instead.
  3. Enter your js code in <js_code> node
  4. If you need others replacements than "%selector%" in your js code, use custom markup like %my-value% in XML, than define them in $js_replacements when you call addPlugin..
Customizing plugin example
$js_replacements = array('%my-value%' => 'replacement-text');
$form->addPlugin('captcha', '$captcha', 'custom', $js_replacements);

Adding your own plugins

Very simple !

  1. Upload your plugin in plugin dir.
  2. Create an XML file with the name of your plugin in plugins-config dir,
    using the tree described in Customizing Plugins section
  3. Call your plugin with addPlugin function

Validation

Overview

Php Form Builder comes with 2 distinct validation systems.

  1. PHP Validation
    Form is validated after being posted. This is a php validation, essential for security.
  2. jQuery Validation
    Fields are validated on the fly, for better User Experience.

Never forget : The only way to avoid security issues is PHP Validation.
Users can easily disable Javascript, and get around jQuery validation.

PHP Validation

PHP Validation Methods

To validate array, use the dot syntax.

Example : <select name="my-field[]" multiple="multiple">

$validator->required()->validate('my-field.0');

        /* if at least 2 values must be selected : */

        $validator->required()->validate(array('my-field.0', 'my-field.1'));

The validation is done with blackbelt's php-validation class.

Complete documentation at https://github.com/blackbelt/php-validation.

I just added these features :

  • Captcha validation support for the included captcha plugin
  • Multilanguage support
  • Patterns validation for the included passfield plugin :
    • $validator->hasLowercase()->validate($field_name);
    • $validator->hasUppercase()->validate($field_name);
    • $validator->hasNumber()->validate($field_name);
    • $validator->hasSymbol()->validate($field_name);
    • $validator->hasPattern('/custom_regex/')->validate($field_name);

Available methods :

  • captcha($field, $message = null) - Added to validate included captcha plugin.
  • recaptcha($secret_key, $message = null) - Added to validate included recaptcha plugin.
  • required($message = null) - The field value is required.
  • email($message = null) - The field value must be a valid email address string.
  • float($message = null) - The field value must be a float.
  • integer($message = null) - The field value must be an integer.
  • digits($message = null) - The field value must be a digit (integer with no upper bounds).
  • min($limit, $include = TRUE, $message = null) - The field value must be greater than $limit (numeric). $include defines if the value can be equal to the limit.
  • max($limit, $include = TRUE, $message = null) - The field value must be less than $limit (numeric). $include defines if the value can be equal to the limit.
  • between($min, $max, $include = TRUE, $message = null) - The field value must be between $min and $max (numeric). $include defines if the value can be equal to $min and $max.
  • minLength($length, $message = null) - The field value must be greater than or equal to $length characters.
  • maxLength($length, $message = null) - The field value must be less than or equal to $length characters.
  • length($length, $message = null) - The field must be $length characters long.
  • matches($field, $label, $message = null) - One field matches another one (i.e. password matching)
  • notMatches($field, $label, $message = null) - The field value must not match the value of $field.
  • startsWith($sub, $message = null) - The field must start with $sub as a string.
  • notStartsWith($sub, $message = null) - The field must not start with $sub as a string.
  • endsWith($sub, $message = null) - THe field must end with $sub as a string.
  • notEndsWith($sub, $message = null) - The field must not end with $sub as a string.
  • ip($message = null) - The field value is a valid IP, determined using filter_var.
  • url($message = null) - The field value is a valid URL, determined using filter_var.
  • date($message = null) - The field value is a valid date, can be of any format accepted by DateTime()
  • minDate($date, $format, $message = null) - The date must be greater than $date. $format must be of a format on the page http://php.net/manual/en/datetime.createfromformat.php
  • maxDate($date, $format, $message = null) - The date must be less than $date. $format must be of a format on the page http://php.net/manual/en/datetime.createfromformat.php
  • ccnum($message = null) - The field value must be a valid credit card number.
  • oneOf($allowed, $message = null) - The field value must be one of the $allowed values. $allowed can be either an array or a comma-separated list of values. If comma separated, do not include spaces unless intended for matching.
  • hasLowercase($message = '') - The field value must contain at least 1 lowercase character.
  • hasUppercase($message = '') - The field value must contain at least 1 uppercase character.
  • hasNumber($message = '') - The field value must contain at least 1 numeric character.
  • hasSymbol($message = '') - The field value must contain at least 1 symbol character.
  • hasPattern($pattern, $message = '') - The field value must match regex.
  • callback($callback, $message = '', $params = array()) - Define your own custom callback validation function. $callback must pass an is_callable() check. $params can be any value, or an array if multiple parameters must be passed.

Validation examples

Validation examples code

Main validation code

if ($_SERVER["REQUEST_METHOD"] == "POST" && Form::testToken('my-form-id') === true) {
    include_once('../Validator/Validator.php');
    include_once('../Validator/Exception.php');
    $validator = new Validator($_POST);
    $required = array('username', 'useremail', 'userphone', 'message'); // required fields
    foreach ($required as $required) {
        $validator->required()->validate($required);
    }
    $validator->email()->validate('email-field-name');
    // add custom message if you want :
    $validator->integer('You must enter a number')->validate('number-field-name');
    $validator->captcha('captcha')->validate('captcha-field-name');
    // check for errors
    if ($validator->hasErrors()) {
        $_SESSION['errors']['my-form-id'] = $validator->getAllErrors();
    }
}

Checkboxes validation

If we want at least one checked :

$form->addCheckbox('chk_group', 'check 1', 1);
$form->addCheckbox('chk_group', 'check 2', 2);
$form->addCheckbox('chk_group', 'check 3', 3);
$form->printCheckboxGroup('chk_group', 'check one : ');

/* Validation : */

if(!isset($_POST['chk_group']) || !is_array($_POST['chk_group'])) {

    /* if none posted, we register error */

    $validator->required('check at least one checkbox please')->validate('chk_group');
}

Radio validation

$form->addRadio('rating', 'Good', 'Good');
$form->addRadio('rating', 'Fair', 'Fair');
$form->addRadio('rating', 'Poor', 'Poor');
$form->printRadioGroup('rating', 'Rate please : ', false, 'required=required');

/* Validation : */

$validator->required('Please rate')->validate('rating');
        

Multiple select validation

$form->addOption('product-choice[]', 'Books', 'Books');
$form->addOption('product-choice[]', 'Music', 'Music');
$form->addOption('product-choice[]', 'Photos', 'Photos');
$form->addSelect('product-choice[]', 'What products are you interested in ?
(multiple choices)', 'required=required, multiple=multiple, style=min-height:130px'); /* Validation : */ $validator->required('Please choose one or several product(s)')->validate('product-choice.0');

Recaptcha validation

$form->addRecaptcha('YOUR_RECAPTCHA_KEY_HERE');

/* Validation : */

$validator->recaptcha('YOUR_RECAPTCHA_SECRET_KEY_HERE', 'Recaptcha Error')->validate('g-recaptcha-response');

Validation multilanguage support

Default language is 'en' (English).

Current available languages are :

  • en
  • de
  • fr
  • pt_br

If you need other language support :

  1. Add your language to form/Validator/Validator.php => _getDefaultMessage($rule, $args = null)
  2. instantiate with your language as second argument :
    $validator = new Validator($_POST, 'fr');

If you add your own language, please share it so it can benefit to other users.

Real time Validation (jQuery)

Getting started

Real time Validation is done with formvalidation plugin.

  1. Call plugin like you would do with any other plugin :
    $form->addPlugin('formvalidation', '#my-form'); // replace "my-form" with your form name
  2. Fields with the following HTML5 types/attributes will be automatically validated :
    min="..."
    max="..."
    maxlength="..."
    minlength="..."
    pattern="..."
    required
    type="color"
    type="email"
    type="range"
    type="url"
    More details here : http://formvalidation.io/examples/html5/
  3. To add any custom validation, use HTML5 attributes with validatorname and validator option :
    <?php
    $form->addInput('text', 'username', 'Username', '', 'data-fv-notempty, data-fv-notempty-message=The username is required and cannot be empty');

    Complete list of HTML5 validation attributes available at http://formvalidation.io/validators/

If you have to use more complex features, or just want to set valodation settings with javascript code instead of HTML5 attributes, you can create a custom config in phpformbuilder/plugins-config/formvalidation.xml

jQuery validation - Available methods

Validator Name HTML5 attributes Description
base64
data-fv-base64         // Enables validation
data-fv-base64-message // (String) - The error message
Validate a base64 encoded string
between
data-fv-between           // Enables validation
data-fv-between-inclusive // (Boolean) - If true, the input value must be in the range strictly
data-fv-between-max       // (Float)   - The upper value in the range.
data-fv-between-message   // (String)  - The error message
data-fv-between-min       // (Float)   - The lower value in the range.
Check if the input value is between (strictly or not) two given numbers
bic
data-fv-bic         // Enables validation
data-fv-bic-message // (String) - The error message
Validate a BIC (Business Identifier Codes)
callback
data-fv-callback          // Enables validation
data-fv-callback-callback // (Function) - The callback method
data-fv-callback-message  //  (String) - The error message.
Return the validity from a callback method
choice
data-fv-choice         // Enables validation
data-fv-choice-max     // (Number) - The maximum number of check boxes required to be checked.
data-fv-choice-message // (String) - The error message.
data-fv-choice-min     // (Number) - The minimum number of check boxes required to be checked.
Check if the number of checked boxes are less or more than a given number
color
data-fv-color         // Enables validation
data-fv-color-message // (String)          - The error message
data-fv-color-type    // (String|String[]) - The type of color.
Validate a color in different formats
creditCard
data-fv-creditcard         // Enables validation
data-fv-creditcard-message // (String) - The error message
Validate a credit card number
cusip
data-fv-cusip         // Enables validation
data-fv-cusip-message // (String) - The error message
Validate a CUSIP
cvv
data-fv-cvv         // Enables validation
data-fv-cvv-ccfield // (String) - The credit card number field. It is null by default
data-fv-cvv-message // (String) - The error message
Validate a CVV number
date
data-fv-date           // Enables validation
data-fv-date-format    // (String) - The date format. It is MM/DD/YYYY, by default
data-fv-date-max       // (String|Date) - The value must be earlier than this option.
data-fv-date-message   // (String) - The error message
data-fv-date-min       // (String|Date) - The value must be later than this option.
data-fv-date-separator // (String) - Used to separate the day, month, and year.
Validate date
different
data-fv-different       // Enables validation
data-fv-different-field // (String) - The name of field that will be used to compare with current one.
                        //            You also can indicate many fields which names are separated by a comma.
Return true if the input value is different with given field's value
digits
data-fv-digits         // Enables validation
data-fv-digits-message // (String) - The error message
Return true if the value contains only digits
ean
data-fv-ean         // Enables validation
data-fv-ean-message // (String) - The error message
Validate an EAN (International Article Number)
ein
data-fv-ein         // Enables validation
data-fv-ein-message // (String) - The error message
Validate an EIN (Employer Identification Number)
emailAddress
data-fv-emailaddress           // Enables validation
data-fv-emailaddress-message   // (String) - The error message
data-fv-emailaddress-multiple  // (String) - Allow multiple email addresses, separated by a comma or semicolon.
                               //            The default value is false
data-fv-emailaddress-separator // (String) - Regex for character or characters expected
                               //            as separator between addresses.
                               // By default, it is /[,;]/, i.e. comma or semicolon
Validate an email address
file
data-fv-file              // Enables validation
data-fv-file-extension    // (String) - The allowed extensions, separated by a comma
data-fv-file-maxfiles     // (Number) - The maximum number of files
data-fv-file-maxsize      // (Number) - The maximum file size in bytes
data-fv-file-maxtotalsize // (Number) - The maximum size in bytes for all files
data-fv-file-minfiles     // (Number) - The minimum number of files
data-fv-file-minsize      // (Number) - The minimum file size in bytes
data-fv-file-mintotalsize // (Number) - The minimum size in bytes for all files
data-fv-file-message      // (String) - The error message
data-fv-file-type         // (String) - The allowed MIME type, separated by a comma.
Validate file
greaterThan
data-fv-greaterthan           // Enables validation
data-fv-greaterthan-inclusive // (Boolean) - If true, the input value must be greater than
                              //             or equal to the comparison one.
data-fv-greaterthan-message   // (String) - The error message.
data-fv-greaterthan-value     // (Float) - The number to make a comparison to.
Return true if the value is greater than or equals to given number
grid
data-fv-grid         // Enables validation
data-fv-grid-message // (String) - The error message.
Validate a GRId (Global Release Identifier)
hex
data-fv-hex         // Enables validation
data-fv-hex-message // (String) - The error message.
Validate a hexadecimal number
iban
data-fv-iban         // Enables validation
data-fv-iban-country // (String) - An ISO-3166 country code.
data-fv-iban-message // (String) - The error message.
data-fv-iban-sepa    // (Boolean) - Set it to true (false) to indicate that the IBAN number
                     //             must be (not be) from SEPA countries.
Validate an International Bank Account Number (IBAN)
id
data-fv-id         // Enables validation
data-fv-id-country // (String) - An ISO-3166 country code.
data-fv-id-message // (String) - The error message.
Validate identification number
identical
data-fv-identical         // Enables validation
data-fv-identical-field   // (String) - The name of field that will be used to compare with current one
data-fv-identical-message // (String) - The error message
Check if the value is the same as one of particular field
imei
data-fv-imei         // Enables validation
data-fv-imei-message // (String) - The error message
Validate an IMEI (International Mobile Station Equipment Identity)
imo
data-fv-imo         // Enables validation
data-fv-imo-message // (String) - The error message
Validate an IMO (International Maritime Organization)
integer
data-fv-integer                    // Enables validation
data-fv-integer-message            // (String) - The error message
data-fv-integer-thousandsseparator // (String) - The thousands separator.
data-fv-integer-decimalseparator   // (String) - The decimal separator.
Validate an integer number
ip
data-fv-ip         // Enables validation
data-fv-ip-ipv4    // (Boolean) - Enable IPv4 validator, default to true
data-fv-ip-ipv6    // (Boolean) - Enable IPv6 validator, default to true
data-fv-ip-message // (String) - The error message
Validate an IP address. Support both IPv4 and IPv6
isbn
data-fv-isbn         // Enables validation
data-fv-isbn-message // (String) - The error message
Validate an ISBN (International Standard Book Number). Support both ISBN 10 and ISBN 13
isin
data-fv-isin         // Enables validation
data-fv-isin-message // (String) - The error message
Validate an ISIN (International Securities Identification Number)
ismn
data-fv-ismn         // Enables validation
data-fv-ismn-message // (String) - The error message
Validate an ISMN (International Standard Music Number)
issn
data-fv-issn         // Enables validation
data-fv-issn-message // (String) - The error message
Validate an ISSN (International Standard Serial Number)
lessThan
data-fv-lessthan           // Enables validation
data-fv-lessthan-inclusive // (Boolean) - If true, the input value must be less than or equal
                           //             to the comparison one.
data-fv-lessthan-message   // (String) - The error message
data-fv-lessthan-value     // (Float) - The number to make a comparison to.
Return true if the value is less than or equals to given number
mac
data-fv-mac         // Enables validation
data-fv-mac-message // (String) - The error message
Validate a MAC address
meid
data-fv-meid         // Enables validation
data-fv-meid-message // (String) - The error message
Validate a MEID (mobile equipment identifier)
notEmpty
data-fv-notempty         // Enables validation
data-fv-notempty-message // (String) - The error message
Check if the value is empty
numeric
data-fv-numeric                     // Enables validation
data-fv-numeric-message             // (String) - The error message
data-fv-numeric-thousandsseparator  // (String) - The thousands separator.
data-fv-numeric-decimalseparator    // (String) - The decimal separator.
Check if the value is numeric
phone
data-fv-phone         // Enables validation
data-fv-phone-country // (String) - An ISO-3166 country code.
data-fv-phone-message // (String) - The error message
Validate a phone number
promise
data-fv-promise         // Enables validation
data-fv-promise-message // (String) - The error message
data-fv-promise-promise // (String|Function) - The callback returns promise instance
Use jQuery's Deferred to validate field's value
regexp
data-fv-regexp                   // Enables validation
data-fv-regexp-message           // (String) - The error message
data-fv-regexp-regexp or pattern // (String) - The Javascript regular expression
Check if the value matches given Javascript regular expression
remote
data-fv-remote             // Enables validation
data-fv-remote-crossdomain // (Boolean) - It's same as the crossDomain option of jQuery's ajax.
data-fv-remote-data        // (Object|Function) - The data sent to remote URL.
                           //                     You don't need to use this option if there is only field,
                           //                     defined as field name, sent to the remote URL.
                           //                     When using data-fv-remote-data attribute,
                           //                     its value must be an encoded JSON string.
data-fv-remote-datatype    // (String) - The type of data which is returned by remote server.
                           //            It's same as the dataType option of jQuery's ajax.
data-fv-remote-delay       // (Number) - The Ajax request created by the remote validator is only fired once
                           //            in the delay duration time.
data-fv-remote-message     // (String) - The error message.
data-fv-remote-name        // (String) - The name of field which need to validate
data-fv-remote-type        // (String) - The method used to send data to back-end. It can be GET default or POST
data-fv-remote-url         // (String|Function) - The remote URL.
data-fv-remote-validkey    // (String) - The valid key. It's valid by default.
                           //            This option is useful when connecting to external remote server or APIs
                           //            provided by 3rd parties.
Perform remote checking via Ajax request
rtn
data-fv-rtn         // Enables validation
data-fv-rtn-message // (String) - The error message
Validate a RTN (Routing transit number)
sedol
data-fv-sedol         // Enables validation
data-fv-sedol-message // (String) - The error message
Validate a SEDOL (Stock Exchange Daily Official List)
siren
data-fv-siren         // Enables validation
data-fv-siren-message // (String) - The error message
Validate a Siren number
siret
data-fv-siret         // Enables validation
data-fv-siret-message // (String) - The error message
Validate a Siret number
step
data-fv-step         // Enables validation
data-fv-step-base    //(Float) - The base value, default to 0
data-fv-step-message // (String) - The error message
data-fv-step-step    // (Float) - The step, default to 1
Check if the value is valid step one
stringCase
data-fv-stringcase         // Enables validation
data-fv-stringcase-case    // (String) - Can be lower (default) or upper
data-fv-stringcase-message // (String) - The error message
Check if a string is a lower or upper case one
stringLength
data-fv-stringlength           // Enables validation
data-fv-stringlength-max       // (Number) - The maximum length.
data-fv-stringlength-message   //(String) - The error message.
data-fv-stringlength-min       // (Number)  - The minimum length.
data-fv-stringlength-utf8bytes //(Boolean) - Evaluate string length in UTF-8 bytes. Default to false
data-fv-stringlength-trim      //(Boolean) - Indicate the length will be calculated after trimming the value or not.
                               //            Default to false
Validate the length of a string
uri
data-fv-uri                    // Enables validation
data-fv-uri-allowlocal         // (Boolean) - Allow the private and local network IP. It is false, by default.
data-fv-uri-message            // (String) - The error message
data-fv-uri-protocol           // (String) - The protocols, separated by a comma.
                               //            By default, it is set to http, https, ftp
data-fv-uri-allowemptyprotocol // (Boolean) - Allow the URI without protocol. Default to false
Validate an URL address
uuid
data-fv-uuid         // Enables validation
data-fv-uuid-message // (String) - The error message
data-fv-uuid-version // (String) - The UUID version. Can be 3, 4, 5 or all (default)
Validate an UUID, support v3, v4, v5
vat
data-fv-vat         // Enables validation
data-fv-vat-country // (String) - An ISO-3166 country code.
data-fv-vat-message // (String) - The error message
Validate VAT number
vin
data-fv-vin         // Enables validation
data-fv-vin-message // (String) - The error message
Validate an US VIN (Vehicle Identification Number)
zipCode
data-fv-zipcode         // Enables validation
data-fv-zipcode-country // (String) - An ISO-3166 country code.
data-fv-zipcode-message // (String) - The error message
Validate a zip code

Multilanguage support

jQuery Validation languages files are in phpformbuilder/plugins/formvalidation/dist/js/language/

To set your language :

  1. Open /phpformbuilder/phpformbuilder/plugins-config/formvalidation.xml
  2. Duplicate <french></french> node with its content, rename it (for example '<german></german>')
  3. Replace all fr_FR occurences with your own language code
  4. Call plugin :
    $form->addPlugin('formvalidation', '#form-name', 'german');

E-mail Sending

2 ways to send posted values by email :

  • sendMail function for simple emails with default template
  • sendAdvancedMail function for advanced mails with attached files, cc, bcc, ... and/or custom template

sendMail function

$sent_message = Form::sendMail($from_email, $adress, $subject, $filter_values);
    /**
    * Simplest way to send email with posted values
    *
    * Detects posted values to send ; removes unwanted values ($filter_values)
    * Tests and secures values to prevent attacks (phpmailer/extras/htmlfilter.php => HTMLFilter)
    * Creates an automatic html table with vars/values based on default template
    * (phpformbuilder/mailer/email-templates/basic-template.[html|css])
    * Merges html/css to inline style
    * Sends email and catches errors
    *
    * @param string $from_email    e-mail adress of the sender
    * @param string $adress        e-mail adress destination
    * @param string $subject       e-mail subject
    * @param string $filter_values posted values you don't want to include in the e-mail,
    *                              separated with commas
    *
    * @return string success or error message
    */
Example
$from_email = [email protected]';
$adress = [email protected]';
$subject = 'contact from my site';
$filter_values = 'my-contact-form, captcha, submit-btn, captchaHash';
$sent_message = Form::sendMail($from_email, $adress, $subject, $filter_values);
echo $sent_message;

Your message has been successfully sent !

sendAdvancedMail function

$sent_message = Form::sendAdvancedMail($options);

To create custom email templates :

  1. Create your html template and save it into phpformbuilder/mailer/email-templates/[your-template-name].html
  2. Put fieldnames between braces in your template ; they'll be replaced automatically with posted values.
    For example : "Hello {user-first-name} {user-name}"
  3. Create a css file in same directory and link it into your html template.
    Example : <link rel="stylesheet" type="text/css" href="[your-template-name].css">
  4. [optional] You can use custom_replacements (see options below) to replace specific texts in email with specific values
  5. Call sendAdvancedMail function (set html_template and css_template options)

html custom template example available at phpformbuilder/mailer/email-templates/contact-email.html

    /**
    * Advanced way to send email with posted values
    *
    * Tests and secures values to prevent attacks (phpmailer/extras/htmlfilter.php => HTMLFilter)
    * Uses custom html/css template and replaces {fields} in template with posted values
    * OR Creates an automatic html table with vars/values based on default template
    * (phpformbuilder/mailer/email-templates/basic-template.[html|css])
    * Merges html/css to inline style
    * Sends email and catches errors
    * @param  array  $options
    *                         from_name [optional]            : the name of the sender
    *                         from_email                      : the email of the sender
    *                         reply_to [optional]             : the email for reply
    *                         adress                          : the email destination(s), separated with commas
    *                         cc [optional]                   : the email(s) of copies to send, separated with commas
    *                         bcc [optional]                  : the email(s) of blind copies to send, separated with commas
    *                         subject                         : The email subject
    *                         attachments [optional]          : file(s) to attach : separated with commas, or array (see details inside function)
    *                         html_template [optional]        : path of the html template to use (path on your server, relative or absolute)
    *                         css_template [optional]         : path of the css template to use (path on your server, relative or absolute)
    *                         filter_values [optional]        : if html_template leaved empty, posted values you don't want to include in the e-mail based on the default template
    *                         custom_replacements [optional]  : array to replace shortcodes in email template. ex : array('mytext' => 'Hello !') will replace {mytext} with Hello !
    *                         sent_message [optional]         : message to display when email is sent
    *                         display_errors [optional]       : displays sending errors
    * @return string sent_message          success or error message to display on the page
    */
Example
$options = array(
    'from_email'     =>  [email protected]',
    'from_name'      =>  'phpformbuilder', // optional
    'reply_to'       =>  [email protected]', // optional
    'adress'         =>  [email protected]',
    'cc'             =>  [email protected]', // optional
    'bcc'            =>  [email protected], [email protected]', // optional
    'subject'        =>  'contact from PHP Form Builder',
    'attachments'    =>  'img/wallacegromit.jpg', // optional
    'html_template'  => '../mailer/email-templates/contact-email.html', // optional
    'css_template'   => '../mailer/email-templates/contact-email.css', // optional
    'filter_values'  => '', // optional
    'custom_replacements'  => array('mytext' => 'Hello !'), // optional
    'sent_message'   => '<p class="alert alert-success">Your message has been successfully sent !</p>', // optional
    'display_errors' => true // optional, default false
);
$sent_message = Form::sendAdvancedMail($options);

Your message has been successfully sent !

Attachments Examples

Examples using FileUpload plugin

The upload path is configured in
phpformbuilder/plugins/jQuery-File-Upload/server/php/[YourFileUploadHandler].php.

The uploaded filename is sent using hidden field, for example $_POST['files'].

Single file :

$path = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/images/uploads/';
$options = array(
    [...]
    'attachments'    =>  $path . $_POST['files'][0]
);
$msg = Form::sendAdvancedMail($options);

Multiple files separated with commas :

$attachments = $path . $_POST['files'][0] . ',' . $path . $_POST['files'][1];
$options = array(
    [...]
    'attachments'    => $attachments,
    [...]
);
$msg = Form::sendAdvancedMail($options);
Examples using input type="file"

Single file :

$form->addInput('file', 'myFile', '', 'file : ');

$attachments = array(
    array(
        'file_path' => $_FILES['myFile']['tmp_name'],
        'file_name' => $_FILES['myFile']['name']
    )
);
$options = array(
    [...]
    'attachments'    => $attachments,
    [...]
);
$msg = Form::sendAdvancedMail($options);

Multiple files :

$form->addInput('file', 'myFile', '', 'file : ');
$form->addInput('file', 'mySecondFile', '', 'file : ');

$attachments = array(
    array(
        'file_path' => $_FILES['myFile']['tmp_name'],
        'file_name' => $_FILES['myFile']['name']
    ),
    array(
        'file_path' => $_FILES['mySecondFile']['tmp_name'],
        'file_name' => $_FILES['mySecondFile']['name']
    )
);
$options = array(
    [...]
    'attachments'    => $attachments,
    [...]
);
$msg = Form::sendAdvancedMail($options);

Database Utilities

Jeff L. Williams's Mysql class is in database folder.

Complete Mysql class doc with examples queries is in phpformbuilder/documentation/mysql-class-doc/

Just configure your localhost/production access in phpformbuilder/database/db-connect.php, and you're ready to connect.

Examples

Database Insert Example
use phpformbuilder\database\Mysql;

require_once 'phpformbuilder/database/db-connect.php';
require_once 'phpformbuilder/database/Mysql.php';

$db = new Mysql();
$insert['ID'] = Mysql::SQLValue('');
$insert['username'] = Mysql::SQLValue($_POST['username']);
$insert['useremail'] = Mysql::SQLValue($_POST['useremail']);
$insert['userphone'] = Mysql::SQLValue($_POST['userphone']);
if (!$db->insertRow('YOUR_TABLE', $insert)) {
    $msg = '<p class="alert alert-danger">' . $db->error() . '<br>' . $db->getLastSql() . '</p>' . " \n";
} else {
    $msg = '<p class="alert alert-success">1 row inserted !</p>' . " \n";
}
echo $msg;

Database Update

Database Update Example
use phpformbuilder\database\Mysql;

require_once 'phpformbuilder/database/db-connect.php';
require_once 'phpformbuilder/database/Mysql.php';

$db = new Mysql();
$filter['ID'] = Mysql::sqlValue($_POST['ID'], Mysql::SQLVALUE_NUMBER);
$update['username'] = Mysql::SQLValue($_POST['username']);
$update['useremail'] = Mysql::SQLValue($_POST['useremail']);
$update['userphone'] = Mysql::SQLValue($_POST['userphone']);
if (!$db->UpdateRows('YOUR_TABLE', $update, $filter)) {
    $msg = '<p class="alert alert-danger">' . $db->error() . '<br>' . $db->getLastSql() . '</p>' . " \n";
} else {
    $msg = '<p class="alert alert-success">Database updated successfully !</p>' . " \n";
}
echo $msg;

Database Delete

Database Delete Example
use phpformbuilder\database\Mysql;

require_once 'phpformbuilder/database/db-connect.php';
require_once 'phpformbuilder/database/Mysql.php';

$db = new Mysql();
$filter["ID"] = Mysql::sqlValue($_POST['ID'], Mysql::SQLVALUE_NUMBER);
if (!$db->deleteRows('YOUR_TABLE', $filter)) {
    $msg = '<p class="alert alert-danger">' . $db->error() . '<br>' . $db->getLastSql() . '</p>' . " \n";
} else {
    $msg = '<p class="alert alert-success">1 row deleted successfully !</p>' . " \n";
}
echo $msg;

Security

Protection against XSS (Cross-Site Scripting)

How it works

  1. When form is created, each fieldname is registered in session
  2. When form is posted, each posted value is registered in session.
  3. If validation is ok, call Form::clear('form-name'); to clear all previously registered values
  4. If validation fails, form will fill fields using user posted values stored in session, protected using htmlspecialchars().

To display posted values on your pages, always protect with htmlspecialchars() : htmlspecialchars($_POST['value'])

To register posted values into your database :

  • protect with addslashes() : addslashes(htmlspecialchars($_POST['value']))
  • or just with addslashes id you want to keep html intact : addslashes($_POST['value'])
  • or use built-in Mysql class protection

Protection against CSRF (Cross-Site Request Forgeries)

Security token is automatically added to each form.

Token is valid for 1800 seconds (30mn) without refreshing page.

Validate posted token this way :

if(Form::testToken('my-form-id') === true) {
        // token valid, no CSRF.
    }

Sources & Credits

Thanks so much to :