1. Code
  2. PHP
  3. PHP Scripts

Create Beautiful Forms With PHP Form Builder

Scroll to top

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.

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:

  • PHP 7.0 or higher, with the cURL extension enabled
  • an Envato account

1. Installing the Library

PHP Form Builder is a premium PHP library available on CodeCanyon. So log in to your Envato account and purchase a license for it.

PHP Form Builder on CodeCanyonPHP Form Builder on CodeCanyonPHP Form Builder on CodeCanyon

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.

1
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.

1
unzip ~/Downloads/codecanyon-8790160-php-form-builder.zip
2
mv phpformbuilder/phpformbuilder ~/my_forms
3
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:

1
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.

PHP Form Builder registration pagePHP Form Builder registration pagePHP Form Builder registration page

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 methods you'll need to create your forms. Here's how you import it:

1
<?php
2
include_once $_SERVER['DOCUMENT_ROOT'] . '/phpformbuilder/Form.php';
3
use phpformbuilder\Form;

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:

1
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:

1
$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:

1
$registrationForm->addInput('text', 'fname', '', 'Full Name');
2
$registrationForm->addInput('text', 'uname', '', 'Username');
3
$registrationForm->addInput('password', 'upasswd', '', 'Password');
4
$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.

1
$registrationForm->addBtn('submit', 'reg-submit', 
2
                            'submit', 'Register');
3
?>

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:

1
<!DOCTYPE html>
2
<html>
3
    <head>
4
    </head>
5
    <body>
6
    </body>
7
</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.

Form without any stylesForm without any stylesForm without any styles

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:

1
<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.

1
<?php
2
  $registrationForm->printIncludes('css');
3
?>

Furthermore, for best results, I suggest you add some padding and margins to the form by enclosing it in a div.

1
<div style='padding:16px;margin:8px;'>
2
    <?php

3
        $registrationForm->render();

4
    ?>
5
</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.

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">
2
</script>
3
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js">
4
</script>
5
6
<?php

7
    $registrationForm->printIncludes('js');

8
    $registrationForm->printJsCode();

9
?>

If you open index.php in a browser now, you'll be able to see that the form looks like this:

Form with styles appliedForm with styles appliedForm with styles applied

In case you were wondering, here's what the form looks like with Materialize as the CSS framework:

Same form but with MaterializeCSSSame form but with MaterializeCSSSame form but with MaterializeCSS

5. Validating Inputs

PHP Form Builder has a Validator class you can use to simplify server-side form validation. Here's how you import it:

1
use phpformbuilder\Validator\Validator;

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.

1
$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.
  • 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:

1
$myForm->startFieldSet('My Little Form')
2
       ->addInput('text', 'name', '', 'Name')
3
       ->addInput('text', 'age', '', 'Age')
4
       ->addInput('text', 'email', '', 'Email')
5
       ->endFieldSet()
6
       ->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.

1
if ($_SERVER["REQUEST_METHOD"] == "POST") {
2
    // More code here    

3
}

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.

1
$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.

1
$validator->minLength(8)->validate('name');
2
$validator->integer()->validate('age');
3
$validator->max(45)->validate('age');
4
$validator->email('Please provide a valid address')
5
          ->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 the 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:

1
if ($validator->hasErrors()) {
2
    $_SESSION['errors']['my-form'] = $validator->getAllErrors();
3
}

If you try submitting the form with invalid values now, you'll be able to see the validator in action.

Form showing error messageForm showing error messageForm showing error message

6. 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:

1
$myForm->addBtn('submit', 'submit', 1, 'Submit', 
2
                'class=btn btn-primary');

With the above change, the button will look like this:

Submit button using a different styleSubmit button using a different styleSubmit button using a different style

One of the best things about using PHP Form Builder is that it supports most Bootstrap themes right out of the box. This means that 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:

1
<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.

Form with Slate themeForm with Slate themeForm with Slate theme

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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.