PHP-Bootstrap-Form
Documentation
Documentation
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
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:
<?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 |
<?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 |
<?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 |
Generates a hidden input element
<?php
Form::Hidden ("id", $attributes = null);
?>
<?php
Form::Textbox ("Text", "text", $attributes = null);
?>
<?php
Form::Number("Number", "Number", $attributes = null);
?>
<?php
$options = Array ("1" => "option #1", "2" => "option #2");
Form::Select("Select", "select", $options, $attributes = null);
?>
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"]);
?>
<?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);
?>
<?php
$options = Array ("1" => "option #1", "2" => "option #2");
Form::Radio("Inline", "id", $options, array("inline" => 1));
Form::Radio("", "id2", $options, $attributes = null);
?>
<?php
Form::Email ("Email Address", "email", $attributes = null);
?>
<?php
Form::Password ("Password", "password", $attributes = null);
?>
<?php
Form::File("File", "file", $attributes = null);
?>
<?php
Form::Textarea("Textarea", "textarea", $attributes = null);
?>
<?php
Form::Phone("Phone", "phone", $attributes = null);
?>
<?php
Form::Search ("Search", "search", $attributes = null);
?>
<?php
Form::Url("Url", "url");
?>
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);
?>
jQuery UI based calendar element. Extra option: jQueryOptions
<?php
Form::jQueryUIDate("Date", "jQueryUIDate", $attributes = null);
?>
<?php
Form::Range("Range", "Range", $attributes = null);
?>
<?php
Form::Color("Color", "Color", $attributes = null);
?>
<?php
Form::State("State", "State", $attributes = null);
?>
<?php
Form::Country("Country", "Country", $attributes = null);
?>
<?php
Form::YesNo("Yes/No", "YesNo", $attributes = null);
?>
<?php
Form::Captcha("Captcha", $attributes = null);
?>
Extra option: jQueryOptions
<?php
$options = Array ("1" => "option #1", "2" => "option #2");
Form::Sort("Sort", "Sort", $options, $attributes = null);
?>
<?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));
?>
Extra attribute: basic
<?php
Form::TinyMCE("Article", "article", $attributes = null);
?>
Extra attribute: basic
<?php
Form::CKEditor("CKEditor", "CKEditor", $attributes = null);
?>
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
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();
?>
form-inline bootstrap form layout.
<?php
Form::open ("test1", $values, "view" = "Inline")
Form::Textbox ("Login", "login");
Form::Textbox ("Login", "password");
Form::close();
?>
Simple vertical layout without labels.
<?php
Form::open ("test1", $values, "view" = "Vertical")
Form::Textbox ("Login", "login");
Form::Textbox ("Login", "password");
Form::close();
?>
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
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. |
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.*/
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