Installation

To start using php-bootstrap-forms it should be included into your project.


    require_once ("PFBC/Form.php");
    

Or it is also possible to install library via composer:


        composer require avbdr/php-bootstrap-form:dev-master
    

Basic usage

Before opening a form please make sure that session is activated. Library is using sessions for server side form validation.

PHP-Bootstrap-Form has support for 32 form elements: Button, Captcha, Checkbox, Checksort, CKEditor, Color, Country, Date, DateTimeLocal, DateTime, Email, File, Hidden, HTML, jQueryUIDate, Month, Number, Password, Phone, Radio, Range, Search, Select, Sort, State, Textarea, Textbox, Time, TinyMCE, Url, Week, YesNo.

Each of HTML5 elements will fallback to textboxes in the event that the HTML5 input type isn't supported in the user's web browser.

In the example below we will create a simple login form and then will explain how it work


<?php
session_start();
Form::open ("login");
    echo "<legend>Login</legend>";
    Form::Hidden ("id");
    Form::Email ("Email Address:", "email", array("required" => 1));
    Form::Password ("Password:", "password", array("required" => 1));
    Form::Checkbox ("", "remember", array("1" => "Remember me"));
    Form::Button ("Login");
    Form::Button ("Cancel", "button", array("onclick" => "history.go(-1);"));
Form::close (false);
?>    

Following code will produce a form like this:

Login

Starting a form


    <?php
        $form = Form::open ($id, $values, $attributes = null);
        $form2 = Form::open ($id2, $values2, $attributes = null);
    ?>    

Form::open() is used to initiate new form. Function will perform internal configurations as well will echo an initial form code. If on the single page multiple forms should be generated it is possible to use an objects returned by Form::open() to relate to the needed form.

Form:open() support all html attributes (including data attributes) plus following library specific attributes:

Attribute Type Description
action String Form action URL. Default is same page
method String Form submit method. Default: POST
ajax String Javascript function to called after the form's data has been submitted. Default is null -- ajax submit disabled
prevent Array Empty by default. Only value could be passed: 'focus' -- disable auto focus of the first form element
view String Form rendering type. Default is 'SideBySide'. Available types: Inline, Search, SideBySide, SideBySide4 and Vertical. See Views for more information
errorView String Error rendering view type. Default: Standart
noLabel Bool If true, render all labels as placeholder

Closing a form


    <?php
        Form::close ();
        Form::close (false);
        Form::close (Form::$SUBMIT);

        $buttons = [
            ["Suspend", "button", ["class" => "btn-danger actionButton", "data-action" => ".."]],
            ["Delete", "button", ["class" => "btn-danger actionButton", "data-action" => ".."]],
        ];
        Form::close ($buttons);
    ?>    

Closing a form internally and will echo form closing code and form related css and js code if needed

$closeType could be one of the following types

Type Description
Form::$SUBMIT Add submit and Cancel button. Close a form after that
Array Add submit, cancel and extra buttons from an array.
false Just close a form. No need to generate extra buttons

Element types

Generic prototype description


    <?php
        Form::ElementType ($label = "", $id = null, $attributes = null);
        Form::ElementType ($label = "", $id = null, $options = Array(), $attributes = null);
    ?>    

All elements falls under this two prototypes.

Variable Type Description
$label String Element label in the form. In case of the 'Vertical' view usage, element label will be rendered as a placeholder
$id String Element ID. If name were not set separately, name will be set to the same value as id. If not set, default id will {$formId}-elem-{$elementCount}
$options Array Used in elements like Option,Radio,Select. Array could be an associative array or a usual array
$attributes Array All elements support all html attributes (including data attributes and html5 validation attributes) plus following library specific attributes:

Library specific attributes:

Attribute Type Description
append String Append addon to the end of element. Ex: "prepend" => "<span class='glyphicon glyphicon-earphone'></span>"
prepend String Prepend addon to the begining of element. Ex: "prepend" => "<span class='glyphicon glyphicon-earphone'></span>"
inline boolean Used in radio and option elements. Indicates if element values should be rendered inline or one after another
minlength int Minimal length validation. No support on client side validation, only server side for now
shared String Element row should be shared between current and next elements. Value should contain bootstrap bootstrap col- sizing definitions. Ex: 'col-xs-5 col-md-4' if you want to fit 2 elements. Note that maximum row size here is 'col-xs-10 colo-md-8'. If bigger size will be specified, your form will be misaligned. See views description for more information.
validation object Validation object. Ex: "validation" => new Validation_Numeric(). See validation for more info

Hidden

Generates a hidden input element


    <?php
        Form::Hidden ("id", $attributes = null);
    ?>    

Textbox


    <?php
        Form::Textbox ("Text", "text", $attributes = null);
    ?>    

Number


    <?php
        Form::Number("Number", "Number", $attributes = null);
    ?>    

Select


    <?php
        $options = Array ("1" => "option #1", "2" => "option #2");
        Form::Select("Select", "select", $options, $attributes = null);
    ?>    

Buttons

Buttons have an extra parameter 'icon' to simplify icons markup. Currently fontawesome and glyphicon prefixes supported. Default markup for icons is span.


    <?php
        Form::Button ("GOGOGO");
        Form::Button ("GOGOGO", "button");
        Form::Button ("GOGOGO", "button", ["class" => "btn-danger"]);
        Form::Button ("GOGOGO", "button", ["icon" => "glyphicon glyphicon-earphone"]);
        Form::Button ("GOGOGO", "button", ["icon" => "fa fa-chrome"]);
    ?>    

Checkboxes


    <?php
    $options = Array ("1" => "option #1", "2" => "option #2");
    // inline checkboxes
    Form::Checkbox ("Inline", "food", $options, array("inline" => 1));

    // regular checkboxes
    Form::Checkbox ("Regular", "food2", $options, $attributes = null);
    ?>    

Options


    <?php
        $options = Array ("1" => "option #1", "2" => "option #2");
        Form::Radio("Inline", "id", $options, array("inline" => 1));
        Form::Radio("", "id2", $options, $attributes = null);
    ?>    

Email


    <?php
        Form::Email ("Email Address", "email", $attributes = null);
    ?>    

Password


    <?php
        Form::Password ("Password", "password", $attributes = null);
    ?>    

File


    <?php
        Form::File("File", "file", $attributes = null);
    ?>    

Textarea


    <?php
        Form::Textarea("Textarea", "textarea", $attributes = null);
    ?>    

Phone


    <?php
        Form::Phone("Phone", "phone", $attributes = null);
    ?>    

Search


    <?php
        Form::Search ("Search", "search", $attributes = null);
    ?>    

URL


    <?php
        Form::Url("Url", "url");
    ?>    

Date Elements

Please note, that usage of date element can lead to a different behavoir in different browsers.


    <?php
        Form::Date("US Date", "date", $attributes = null);
        Form::Date("EU Date", "date", array ("pattern" => "\d{2}.\d{2}.\d{4}",
                                             "placeholder" => "DD.MM.YYYY"));
        Form::DateTime("DateTime", "datetime", $attributes = null);
        Form::DateTimeLocal("DateTime Local", "DateTimeLocal", $attributes = null);
        Form::Month("Month", "month", $attributes = null);
        Form::Week("Week", "week", $attributes = null);
        Form::Time("Time", "time", $attributes = null);
    ?>    

Calendar

jQuery UI based calendar element. Extra option: jQueryOptions


    <?php
        Form::jQueryUIDate("Date", "jQueryUIDate", $attributes = null);
    ?>    

Range


    <?php
        Form::Range("Range", "Range", $attributes = null);
    ?>    

Color


    <?php
        Form::Color("Color", "Color", $attributes = null);
    ?>    

State


    <?php
        Form::State("State", "State", $attributes = null);
    ?>    

Country


    <?php
        Form::Country("Country", "Country", $attributes = null);
    ?>    

Yes-No Question


    <?php
        Form::YesNo("Yes/No", "YesNo", $attributes = null);
    ?>    

Captcha


    <?php
        Form::Captcha("Captcha", $attributes = null);
    ?>    

Sort

Extra option: jQueryOptions


    <?php
        $options = Array ("1" => "option #1", "2" => "option #2");
        Form::Sort("Sort", "Sort", $options, $attributes = null);
    ?>    
  • option #1
  • option #2

Checksort


    <?php
        $options = Array ("1" => "option #1", "2" => "option #2");
        Form::Checksort("Checksort", "Checksort", $options, $attributes = null);
        Form::Checksort("Checksort inline ", "Checksort", $options, array("inline" => 1));
    ?>    

      TinyMCE Editor

      Extra attribute: basic

      
          <?php
              Form::TinyMCE("Article", "article", $attributes = null);
          ?>    

      CKEditor

      Extra attribute: basic

      
          <?php
              Form::CKEditor("CKEditor", "CKEditor", $attributes = null);
          ?>    

      Views

      Views are responsible for converting a form's properties and elements into HTML, CSS, and javascript for the browser to display. There are 4 views available: SideBySide, SideBySide4 (boostrap4), Vertical and Inline.

      For bootstrap support use SideBySide4 view

      SideBySide View

      Default library view type. form-horizonal bootstrap form layout.

      
          <?php
              Form::open ("test1", $values)
              Form::Textbox ("Login", "login");
              Form::Textbox ("Login", "password");
              Form::Button ("GO");
              Form::close();
          ?>    

      Inline View

      form-inline bootstrap form layout.

      
          <?php
              Form::open ("test1", $values, "view" = "Inline")
              Form::Textbox ("Login", "login");
              Form::Textbox ("Login", "password");
              Form::close();
          ?>    

      Vertical View

      Simple vertical layout without labels.

      
          <?php
              Form::open ("test1", $values, "view" = "Vertical")
              Form::Textbox ("Login", "login");
              Form::Textbox ("Login", "password");
              Form::close();
          ?>    

      Ajax

      PHP-Bootstrap-Form provides a very simple way for ajax form submissions. To get started, you'll first need to set the 'ajax' property in the form attributes with a name of a javascript callback function to called after the form's data has been submitted.

      Please note, that json reply should come with a content-type set to application/json or it will be ignored.

      ajax submit example:

      
      <?php
      Form::open ("test", $values, ["ajax" => "finishCallback"]);
      Form::hidden ("id");
      From::Button ("Submit");
      Form::close ();
      ?>
      <script>
      function finishCallback (data) {
          console.log (data.status);
          console.log (data.message);
      }
      </script>    

      Reply example

      
      <?php
          $reply = ["status" => "OK", "message" => "all is good"];
          header ("Content-type: application/json");
          echo json_encode ($reply);
      ?>

      See an example here

      Validation

      Client-Side validation and Validation types

      PHP-Bootstrap-Form validation is achieved in a two step process. The first step is to apply validation rules to form elements via the element's validation attribute. Some elements including Captcha, Color, Date, Email, jQueryUIDate, Month, Number, Url, and Week have validation rules applied by default.

      PHP-Bootstrap-Form supports 7 types of validation rules: AlphaNumeric, Captcha, Date, Email, Numeric, RegExp, Required, and Url,

      Type Description
      Validation_Required ()
      Validation_AlphaNumeric () AlphaNumeric validation class will verify that the element's submitted value contains only letters, numbers, underscores, and/or hyphens
      Validation_Numeric () Number element applies the Numeric validation rule by default. If supported, HTML5 validation will also be provided client-side.
      Validation_Email () Email element applies the Email validation rule by default. If supported, HTML5 validation will also be provided client-side.
      Validation_Date () Date element applies the RegExp validation rule by default - ensuring the following date format YYYY-MM-DD is adhered to.
      Validation_RegExp ($regExp, $errorMessage) RegExp validation class provides the means to apply custom validation to an element. Its constructor includes two parameters: the regular expression pattern to test and the error message to display if the pattern is not matched.
      Validation_Captcha () Captcha element applies the Captcha validation, which uses reCaptcha's anti-bot service to reduce spam submissions.
      Validation_Url () The Url element applies the Url validation rule by default. If supported, HTML5 validation will also be provided client-side.

      Server-side validation

      Secondly, you need to call Form::isValid() static method once the form's data has been submitted. This function will return true/false. If false is returned, it indicates that one or more errors occurred. You will then need to redirect users back to the form to correct and resubmit.

      The validation process for an ajax submission also differs slightly from that of a standard submission. If the form's isValid method returns false, you will need to invoke the renderAjaxErrorResponse method, which returns a json response containing the appropriate error messages. These errors will then be displayed in the form so the user can correct and resubmit.

      Below is an example of the isValid use.

      
          <?php
          //----------AFTER THE FORM HAS BEEN SUBMITTED----------
          include("PFBC/Form.php");
          if(!Form::isValid("<replace with unique form identifier>")) {
              /* Validation errors have been found.  We now need to redirect users back to the 
              form back so the errors can be corrected and the form can be re-submitted.
                 In case of ajax submit Form::renderAjaxErrorResponse () will build an error reply.*/
      
              if ($reqIs("AJAX")) {
                  header ("Content-type: application/json");
                  Form::renderAjaxErrorResponse($formName);
              } else
                  header("Location: <replace with form url>");
          }
          //form submitted data has been validated.  Your script can now proceed with any 
          further processing required.*/    

      Custom Validation

      Often times, you'll find that you need to apply custom validation to your forms' submitted data. For instance, if you create a login form, you'll need to validate user entered credentials against your system. PHP-Bootstrap-Form has several methods that support this type of scenario. Let's take a look at an example implementation.

      
          <?php
      //----------AFTER THE FORM HAS BEEN SUBMITTED----------
      include("PFBC/Form.php");
      if(Form::isValid("login", false)) {
          if(isValidUser($_POST["Email"], $_POST["Password"])) {
              Form::clearValues("login");
              header("Location: profile.php");
          }
          else {
              Form::setError("login", "Error: Invalid Email Address / Password");
              header("Location: login.php");
          }
      }
      else
          header("Location: login.php");
          

      The isValid method has a second, optional parameter that controls whether or not the form's submitted data is cleared from the PHP session if the form validates without errors. In the example above, false is passed allowing us to authenticate the potential user with the fictional isValidUser function. If the user's credentials are valid, the session data is cleared manually with the clearValues method, and we redirect the user to their profile page. If invalid credentials were supplied, we use the setError method to manually set a custom error message and redirect back to the login form so the user can resubmit.

      TODO