Php Form Builder's Beginners Guide

Welcome to Php Form Builder's Beginners Guide

Here you'll learn in a few steps how to :

For any question or request

Please

Install and run a local PHP server

  1. Download and install a php server - this is required to run php on your computer.

    Most well-known are :

You'll find numerous pages and videos about how to install and run your php server.

Check your PHP version

  1. Create a new empty file at the root of your project, named for example test-form.php.

  2. Add the following line into your file :

    <?php phpinfo(); ?>
  3. Open your favorite browser and go to your file's url, for example : http://localhost/my-project/test-form.php

  4. If your version is php 5.3 or newer, you're on the right track.

    If not, you've got to upgrade your php to a most recent version.

Include required files on your page to build form

  1. Open your test-form.php (see previous chapter) using your favourite editor

  2. Add html basic markup :

    <!DOCTYPE html>
    <html>
    <head>
        <title>Test Form</title>
        <!-- Latest compiled and minified Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    </head>
    <body>
        <h1>My first form</h1>
        <!-- Latest compiled and minified jQuery -->
        <script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
        <!-- Latest compiled and minified Bootstrap JS -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    </body>
    </html>
  3. Now add the following code at the very beginning of your file :

    <?php
    use phpformbuilder\Form;
    use phpformbuilder\Validator\Validator;
    session_start();
    include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/Form.php';
    ?>

    This code will be the same for all pages containing forms.

    <?php
    // Following 2 lines are required since php 5.3 to set namespaces.
    // more details here : http://php.net/manual/en/language.namespaces.php
    use phpformbuilder\Form;
    use phpformbuilder\Validator\Validator;
    
    // Following line starts php session. That's to say we'll memorize variables in php session.
    session_start();
    
    // Then we include main form class, which contains all functions to build forms.
    include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/Form.php';
    ?>
  4. Refresh your test-form.php in your browser (http://localhost/my-project/test-form.php)

    If you see a blank page, all is ok, you can go on to next step

    If your browser throws an error 500, click button below to solve this.

    Your browser has thrown this error because php can't find Form.php.

    rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) should lead to the root of your project.
    If works fine if your server is well configured, but it seems that's not the case.

    To solve this, try to replace include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/Form.php'; with one of the following :

    • include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Form.php';
    • include_once $_SERVER['DOCUMENT_ROOT'] . 'phpformbuilder/Form.php';
    • include_once 'phpformbuilder/Form.php';

    You've got to find the right path to Form.php, it can be absolute or relative path.

Configure your plugins path

  1. open phpformbuilder/plugins-path.php

  2. Line 10 is the root url of plugins dir on your localhost : define('PLUGINS_DIR', '/phpformbuilder/plugins/');

    if phpformbuilder is at the root of your project you don't have to modify anything.

    else, locate your plugins dir url, for example define('PLUGINS_DIR', '/some-dir/phpformbuilder/plugins/');

  3. Line 12 is the root url of plugins dir on your production server.

    Replace 'http://phpformbuilder.creation-site.org/phpformbuilder/plugins/' with your own url.

Build your first form

So let's start building the form.

  1. To create a new form, add this line just after include_once [...] :

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

    $form = new Form('test-form', 'horizontal', 'novalidate');
    // this function creates a new form object.
    
    // arguments :
    //      'test-form'  : this is the form name
    //      'horizontal' : this will add class="form-horizontal"
    //      'novalidate' : this will add 'novalidate' attribute. It prevents browser to use browser's html5 built-in validation.
    
    // You can skip 'novalidate' argument if you want to use browser's html5 built-in validation.
    
    // If you want Material Design style, instanciate this way :
    $form = new Form('test-form', 'horizontal', 'novalidate', 'material');
    
    // or without html5 validation :
    $form = new Form('test-form', 'horizontal', '', 'material');
  2. Add the following line to create an input field :

    $form->addInput('text', 'user-name', '', 'Name :', 'required, placeholder=Name');

    $form->addInput('text', 'user-name', '', 'Name :', 'required, placeholder=Name');
    // this function adds an input to your form.
    
    // arguments :
    //      'text'      : the html input type. can be for example 'text' or 'hidden', 'email', 'number', ...
    //      'user-name' : the html "name" attribute
    //      'Name :'    : label content displayed on screen
    //      'required, placeholder=Name' : can be any html addributes, separated with commas and without quotes.
  3. Add the following line to create 2 radio buttons with iCheck plugin

    $form->addRadio('is-all-ok', 'Yes', 1);
    $form->addRadio('is-all-ok', 'No', 0);
    $form->printRadioGroup('is-all-ok', 'Is all ok ?', false, 'required');
    $form->addPlugin('icheck', 'input', 'default', array('%theme%' => 'square', '%color%' => 'red'));

    // add 2 radio buttons.
    // arguments :
    //      'is-all-ok'   : radio groupname
    //      'Yes'         : radio label
    //      1                       : radio value
    $form->addRadio('is-all-ok', 'Yes', 1);
    $form->addRadio('is-all-ok', 'No', 0);
    
    // render radio group
    // arguments :
    //      'is-all-ok'   : radio groupname
    //      'Is all ok ?' : radio group  label
    //      false                   : inline (true or false)
    //      'required'    : this will add 'required' attribute. can contain any html attribute(s), separated with commas.
    $form->printRadioGroup('is-all-ok', 'Is all ok ?', false, 'required');
    
    // Add iCheck plugin (beautiful radio buttons)
    // arguments :
    //      'input'   : plugin's target (jQuery selector)
    //      'default' : plugin's config (see class doc for details please)
    //      array([...])        : arguments sended to plugin (see class doc for details please)
    $form->addPlugin('icheck', 'input', 'default', array('%theme%' => 'square', '%color%' => 'red'));
  4. Add the submit button :

    $form->addBtn('submit', 'submit-btn', 1, 'Send', 'class=btn btn-success');

    $form->addBtn('submit', 'submit-btn', 1, 'Send', 'class=btn btn-success');
    // this function adds a button to your form.
    
    // arguments :
    //      'submit'      : the html button type.
    //      'submit-btn'  : the html "name" attribute
    //      'Send :'      : Button text content displayed on screen
    //      'class=btn btn-success' : can be any html addributes, separated with commas and without quotes.
  5. Well done. Now the form is ready with an input and a submit button.

    Last step is to render it on page.We'll add 3 php blocks.

    1. Just before </head> :

      <?php $form->printIncludes('css'); ?>
    2. Anywhere between <body></body> :

      <?php
      if (isset($sent_message)) {
          echo $sent_message;
      }
      $form->render();
      ?>
    3. Just before </body> :

      <?php
          $form->printIncludes('js');
          $form->printJsCode();
      ?>

    // Following lines will include jQuery plugin's css files if your form uses plugins.
    <?php $form->printIncludes('css'); ?>
    
    // following lines will render the form in your page, and display success / error message if form has been posted by user.
    <?php
    if (isset($sent_message)) {
        echo $sent_message;
    }
    $form->render();
    ?>
    
    // Following lines will include jQuery plugin's js files if your form uses plugins.
    <?php $form->printIncludes('js'); ?>
  6. Refresh your test-form.php in your browser (http://localhost/my-project/test-form.php)

    your form should be displayed.

Validate user's posted values and send email

Add this php block just after include_once [...] . '/phpformbuilder/Form.php'; :

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Validator/Validator.php';
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Validator/Exception.php';
    $validator = new Validator($_POST);
    $required = array('user-name', 'is-all-ok');
    foreach ($required as $required) {
        $validator->required()->validate($required);
    }
    if ($validator->hasErrors()) {
        $_SESSION['errors']['test-form'] = $validator->getAllErrors();
    } else {
        $from_email = 'contact@my-site.com';
        $adress = 'recipient-email@my-site.com';
        $subject = 'Test form email';
        $filter_values = 'submit-btn';
        $sent_message = Form::sendMail($from_email, $adress, $subject, $filter_values);
        Form::clear('test-form');
    }
}

Email sending may fail on your localhost, depending on your configuration.

It should work anyway on production server.

// if form has been posted
if ($_SERVER["REQUEST_METHOD"] == "POST" && Form::testToken('test-form') === true) {

    // include validation class to test posted values
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Validator/Validator.php';
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Validator/Exception.php';

    // create a new validator object
    $validator = new Validator($_POST);

    //create an array with required values
    $required = array('user-name', 'is-all-ok');

    // loop inside required values and test each one
    foreach ($required as $required) {
        $validator->required()->validate($required);
    }

    // store errors in session if any
    if ($validator->hasErrors()) {
        $_SESSION['errors']['test-form'] = $validator->getAllErrors();
    } else {

        // all is ok, send email
        // Php Form Builder will add all posted labels and values to your message,
        // no need to do anything manually.
        $from_email = 'contact@my-site.com';
        $adress = 'recipient-email@my-site.com';
        $subject = 'Test form email';

        // filter_values are posted values you don't want to include in your message. Separated with commas.
        $filter_values = 'submit-btn';

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

        // clear session values : next time your form is displayed it'll be emptied.
        Form::clear('test-form');
    }
}

Complete page code

<?php
use phpformbuilder\Form;
use phpformbuilder\Validator\Validator;
session_start();
include_once rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR) . '/phpformbuilder/Form.php';
if ($_SERVER["REQUEST_METHOD"] == "POST" && Form::testToken('test-form') === true) {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpforms/Validator/Validator.php';
    include_once $_SERVER['DOCUMENT_ROOT'] . '/phpforms/Validator/Exception.php';
    $validator = new Validator($_POST);
    $required = array('user-name', 'is-all-ok');
    foreach ($required as $required) {
        $validator->required()->validate($required);
    }
    if ($validator->hasErrors()) {
        $_SESSION['errors']['test-form'] = $validator->getAllErrors();
    } else {
        $from_email = 'contact@my-site.com';
        $adress = 'recipient-email@my-site.com';
        $subject = 'Test form email';
        $filter_values = 'submit-btn';
        $sent_message = Form::sendMail($from_email, $adress, $subject, $filter_values);
        Form::clear('test-form');
    }
}
$form = new Form('test-form', 'horizontal', 'novalidate');
$form->addInput('text', 'user-name', '', 'Name :', 'required, placeholder=Name');
$form->addRadio('is-all-ok', 'Yes', 1);
$form->addRadio('is-all-ok', 'No', 0);
$form->printRadioGroup('is-all-ok', 'Is all ok ?', false, 'required');
$form->addPlugin('icheck', 'input', 'default', array('%theme%' => 'square', '%color%' => 'red'));
$form->addBtn('submit', 'submit-btn', 1, 'Send', 'class=btn btn-success');
?>
<!DOCTYPE html>
<html>
<head>
    <title>Test Form</title>
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <?php $form->printIncludes('css'); ?>
</head>
<body>
    <h1>My first form</h1>
    <?php
    if (isset($sent_message)) {
        echo $sent_message;
    }
    $form->render();
    ?>
    <!-- Latest compiled and minified jQuery -->
    <script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
    <!-- Latest compiled and minified Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    <?php
    $form->printIncludes('js');
    $form->printJsCode();
?>
</body>
</html>

To go further

Now you've learned the basics ; Several resources will help to add other fields, plugins, validate different values and build more complex layouts :