If you are a PHP developer, creating forms, validating form submissions, and managing PHP sessions are probably tasks that are part and parcel of your job. All these tasks, although rather repetitive, require lots of time and attention, especially if you care about best practices relating to design and security.
By using a well-tested form builder library, you can significantly improve not only your own efficiency, but also the robustness of your PHP applications. CodeCanyon has a large variety of premium form builder libraries for you to choose from. PHP Form Builder, developed by Envato author migli, is one of them.
-
Looking for a PHP form builder for your website? Today, we compare the five best PHP form generators available at CodeCanyon. This post will help you decide…
-
This tutorial will teach you how to create your own basic contact form in PHP. You will also learn how to validate and sanitize user input to make the form…
-
Contact forms are a must have for every website, and whether your need is for a simple three-line contact form or a more complex one that offers loads of…
-
In this tutorial, you will learn how to send email in PHP after gathering data from different forms filled out by users.
PHP Form Builder supports modern CSS frameworks such as Materialize, Foundation, and Bootstrap 4, and both client-side and server-side form validation. It also includes several pre-built form templates, jQuery plugins, and database utilities.
In this tutorial, I’ll show you how to perform common form-related operations using PHP Form Builder.
Prerequisites
To make the most of this tutorial, you’ll need:
1. Installing the Library
PHP Form Builder is premium PHP library available on CodeCanyon. So log in to your Envato account and purchase a license for it.
You’ll now be able to download a file named codecanyon-8790160-php-form-builder.zip. Make sure this file is available on your development server.
I suggest you create a new project directory to store all the files you’ll be creating and using in this tutorial.
mkdir my_forms
Next, extract the ZIP file you downloaded. Inside the parent directory named phpformbuilder, in addition to the source code, you’ll find various templates, assets, and help files.
Usually you’ll only need the phpformbuilder sub-directory. So move it to the project directory.
unzip ~/Downloads/codecanyon-8790160-php-form-builder.zip mv phpformbuilder/phpformbuilder ~/my_forms cd my_forms
2. Registering the Library
If you purchased a regular license, you’ll be able to use the library locally on your development server and on one domain in production. For now, let’s register the library only from the development server.
Start by launching a PHP development server. Here’s how you can start one to listen on port 8000
:
php -S localhost:8000
Alternatively, feel free to use the Apache web server instead.
You must now open a browser and visit the local registration URL, which looks like this: http://localhost:8000/phpformbuilder/register.php
In the form shown, enter your purchase code, which you’ll find in the purchase confirmation email sent by CodeCanyon, and press the Register button.
Once the registration is successful, you can start using the library.
It’s important to note that if you want to use this library in production, you’ll have to complete this registration process from your production server too.
3. Creating a Simple Form
Create a new file named index.php and open it using a text editor. We’ll be writing all our code inside this file.
PHP Form Builder’s Form
class has most of the method’s you’ll need to create your forms. Here’s how you import it:
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Form.php'; use phpformbuilderForm;
It’s usually a good idea to use a PHP session while handling form data. So now would be a good time to start a new session:
session_start();
To create a new form, you must create an instance of the Form
class, whose constructor expects the name of the form as an argument. For now, let’s create a simple user registration form:
$registrationForm = new Form('reg-form');
To add input fields to the form, you can use the addInput()
method, which expects the type of the field, its name, its default value, and its label. Except for the name and type, all other arguments are optional.
The following code shows you how to create a few different types of fields:
$registrationForm->addInput('text', 'fname', '', 'Full Name'); $registrationForm->addInput('text', 'uname', '', 'Username'); $registrationForm->addInput('password', 'upasswd', '', 'Password'); $registrationForm->addInput('email', 'email', '', 'Email');
To add a submit button to the form, use the addBtn()
method, which is very similar to the addInput()
method.
$registrationForm->addBtn('submit', 'reg-submit', 'submit', 'Register'); ?>
4. Rendering the Form
Our form is now complete. But we’re going to need some HTML boilerplate before we can render it. So, after closing the PHP tag, add the following code, which creates an empty HTML document:
<!DOCTYPE html> <html> <head> </head> <body> </body> </html>
At this point, by calling the render()
method of the Form
object inside the <body>
of the document, you can render your form. It will, however, be very plain looking.
Therefore, before calling the render()
method, you must remember to add a few stylesheets and JavaScript files to the document.
PHP Form Builder supports many popular CSS frameworks. It’s your responsibility to include the latest CSS and JS files of the framework you wish to use. In this tutorial, we’ll be using the Twitter Bootstrap 4.3 framework.
So, inside the <head>
of the document, add a <link>
tag that points to Bootstrap’s stylesheet. If you don’t have it locally, you can always use a CDN. Here’s how:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
PHP Form Builder has its own styles too, which you must add to the document. You can do so by calling the printIncludes()
utility method.
<?php $registrationForm->printIncludes('css'); ?>
Furthermore, for best results, I suggest you add some padding and margins to the form by enclosing it in a div
.
<div style='padding:16px;margin:8px;'> <?php $registrationForm->render(); ?> </div>
Towards the end of the <body>
, you must also include jQuery and Bootstrap 4’s JavaScript files.
Lastly, you must include PHP Form Builder’s own JavaScript files and code by calling the printIncludes()
and printJsCode()
methods.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"> </script> <?php $registrationForm->printIncludes('js'); $registrationForm->printJsCode(); ?>
If you open index.php in a browser now, you’ll be able to see that the form looks like this:
In case you were wondering, here’s what the form looks like with Materialize as the CSS framework:
4. Validating Inputs
PHP Form Builder has a Validator
class you can use to simplify server-side form validation. Here’s how you import it:
use phpformbuilderValidatorValidator;
For the sake of another example, let us now create a simple form whose inputs we can validate. Because we’ll be validating the inputs on the server-side, we must pass novalidate
as an argument to the constructor of the Form
class. This turns off the browser’s default, client-side validation logic, allowing users to submit the form regardless of validation errors.
$myForm = new Form('my-form', 'horizontal', 'novalidate');
Our new form is going to accept a name, an age, and an email address with the following conditions: the name must be at least eight characters long, the age must be an integer that’s less than 45, and the email address must be a valid one.
Here’s how to use the addInput()
and addBtn()
methods, which you are already familiar with, to create the three fields and a submit button:
$myForm->startFieldSet('My Little Form') ->addInput('text', 'name', '', 'Name') ->addInput('text', 'age', '', 'Age') ->addInput('text', 'email', '', 'Email') ->endFieldSet() ->addBtn('submit', 'submit', 1, 'Submit');
As you can see in the code above, PHP Form Builder supports method chaining. The startFieldSet()
and endFieldSet()
methods, as you may have guessed, allow you to group your inputs and add a header to them.
The form validation process should run only after the user has submitted the form. To detect this event, all you need to do is check if the page was accessed using the HTTP POST method.
if ($_SERVER["REQUEST_METHOD"] == "POST") { // More code here }
Inside the if
statement, you can go ahead and create an instance of the Validator
class by calling the validate()
method, which expects the name of the form you want to validate.
$validator = Form::validate('my-form');
The Validator
object has several intuitively-named methods to validate input fields. For instance, you can use the minLength()
method to check if the value of the name
field is at least eight characters long. Similarly, you can use the integer()
and max()
methods to check if the age
is an integer that’s less than 45.
All the validation methods automatically generate meaningful error messages when necessary. If you’re not satisfied with them, however, you are free to provide your own custom messages.
$validator->minLength(8)->validate('name'); $validator->integer()->validate('age'); $validator->max(45)->validate('age'); $validator->email('Please provide a valid address') ->validate('email');
After you’ve added all the checks, you must remember to call the hasErrors()
method to check if any of them failed.
In case of failed checks, the getAllErrors()
method returns all the error messages. To display them, you must update the $_SESSION
variable. The following code shows you how:
if ($validator->hasErrors()) { $_SESSION['errors']['my-form'] = $validator->getAllErrors(); }
If you try submitting the form with invalid values now, you’ll be able to see the validator in action.
5. Adding Styles
PHP Form Builder allows you to manually assign CSS classes to your form fields. Both the addInput()
and the addBtn()
methods accept a fifth parameter, which you can use to customize the associated field.
The following code shows you how to add the btn
and btn-primary
CSS classes to the submit button:
$myForm->addBtn('submit', 'submit', 1, 'Submit', 'class=btn btn-primary');
With the above change, the button will look like this:
One of the best things about using PHP Form Builder is that it supports most Bootstrap themes right out of the box. This means, switching from one Bootstrap theme to another is extremely easy.
All this while, we were using the default Bootstrap theme. To switch to one of the free themes available on Bootswatch, all you need to do is change the <link>
tag you added earlier. Here’s how you can use the Slate theme:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.3.1/slate/bootstrap.min.css" />
With this new theme, as you can see in the screenshot below, the form’s look and feel is very different.
Conclusion
You now know how to create good-looking forms and handle form submissions using PHP Form Builder. In this tutorial, you also saw how easy it is to use custom CSS styles and themes to beautify your forms.
To learn more, do refer to the extensive documentation present in the ZIP file you downloaded.