FormBuilder: HTML forms made simple
Even though HTML forms tend to be much of a muchness, each is different enough to require customized markup, styling, and validation. Sometimes it feels like reinventing the wheel. Over the past year I have been progressively streamlining the way I build my forms, and recently got to a point where I realized it wouldn’t take much more work to create an all-in-one PHP class that generates form markup, validates input, and displays error messages to the user. So that’s what I did, and I’m sharing it here in the hope someone else finds it useful too.
FormBuilder features
FormBuilder is designed to do make building forms simple. It can do pretty much everything you might want to achieve with a typical HTML form:
- Create HTML forms by entering a few PHP values
- Generates XHTML 1.0 Strict compliant markup
- Fully skinnable via CSS
- Rigorous and flexible form validation on a per-field basis
- Displays easy to understand error messages to the user
- Highlights required fields and fields that are in error
- Automatically send form results to any email address
- Displays a ‘thanks’ message once form is successfully processed
- Hide or show HTML content based on whether the form was successfully submitted
- Ability to add your own custom form validation after FormBuilder has completed its own validation pass
- Protect against PHP header injection
Demo and download
I put together a demo page that shows FormBuilder in action. Try filling out the form incorrectly to see examples of FormBuilder’s error messaging.
View FormBuilder demo
Demonstrates default FormBuilder setup.
View FormBuilder ‘pretty’ demo
Demonstrates the showDividers and usePseudoLegends options. These make your forms easier to style but less semantic.
Download FormBuilder (current version is v1.5)
Important: FormBuilder is a work in progress, so I can’t promise it’s completely bug free. Feedback, suggestions and bug reports are welcomed: leave a comment below.
How the heck do I use this thing?
You should be able to get a pretty good idea how FormBuilder works just by looking at the source code of index.php in the download package. If you want to dig a little deeper I included a text file with the package that documents all aspects of the class and how to use it. And if you’re still scratching your head feel free to post a comment below.
Requirements
FormBuilder must be run on a web server with PHP 4+ running (I’ve tested under both PHP4 and PHP5). A basic understanding of PHP is helpful, but if you follow the examples provided in the documentation you might be able to make do without. CSS knowledge is required if you want to change the appearance of the form.
AJAX validation
Over at roScripts there is a nice tutorial explaining how to modify FormBuilder so that validation is performed unobtrusively using AJAX.
Changelog
Version 1.5
- Better handling of checkbox results in the
emailResultsmethod. - A custom form submit URL can be passed to the FormBuilder constructor. Useful when using FormBuilder in an environment that is performing URL rewriting.
- Replaced deprecated
ergeifunctions withpreg_match. - Checkbox field types are correctly processed when field is not mandatory, and the user didn’t check any of the available options.
- Added new field type: file (for file uploads). Note that files are currently not emailed when using the
emailResultsmethod. Any handling of the uploaded files should be accomplished manually by accessing PHP’s$_Filesarray. - The textbox and textarea field types now accept an optional
defaultvalueparameter. - Fixed a bug that meant checkboxes had a CSS class of ‘fbheckbox’ instead of ‘fbcheckbox’.
Version 1.4
- Added
emailResultsfunction, which automatically emails the form variables to any email address
Version 1.3
- Added new field type: password
- Added new field type: hidden
Version 1.2
- By default there is no longer an empty
ddafter each form field, which makes FormBuilder’s markup more semantic. The emptydd's provide a handy element for styling visual dividers between fields, so you can still reveal them using the newshowDividersparameter in the FormBuilder constructor. - Introduced
usePseudoLegendsparameter. If set to true,legendwill be replaced withh3. The HTMLlegendelement is notoriously difficult to style consistently, and this parameter provides a workable alternative. - Cleaned up the demo CSS styles, including getting dividers displaying properly in Safari.
Version 1.1
- Checkboxes and radio buttons are now correctly marked up inside label tags
- Labels are now associated with the relevant form field via the
forattribute
Credit where credit is due
FormBuilder uses validaForms by Erick Vavretchek for form validation. Please see the validaForms PHP Classes package if you wish to learn more about this excellent from validator.
Tweet
Hi, i found it difficult to adjust the form. Example:
I have these 2 related fields: postalcode and city. Here in the Netherlands PC is only 6chars, so i fully width field would be stupid. Therefore I would like to combine PC and City at one height. But of course, keep the input fields seperated.
PC + City [input filed] __ [longer input field]
Because all dd’s and dt’s are styled the sameway I wonder if it’s possible at all… Please contact me, your formbuilder rocks ass! really
@Tobias – I can’t immediately think of a way to achieve what you want. You should be able to style individual fields via CSS, since each field has an id – for instance you could make the postcode field shorter. But targeting field labels would be trickier. If you used javascript (maybe jquery) you might be able to attach CSS classes to specific label, dd or dt elements and wrestle more control over the way they are styled.
@Jonathan: Well that might be one way, but I found it not worth the effort. the script is nice if you need what it does, so I still use it now and then but for more “complicated” forms, i’ll stick to my own forms.
@Tobias – Agreed! There’s a limit to how flexible my script is, and for complex form layouts you are better off rolling your own.
Is there a way to pass a default value into the text forms from a variable? For example:
$contactForm->addField(array (
‘id’ => ‘guess_city’,
‘type’ => ‘textbox’,
‘label’ => ‘The City You Are In’,
‘required’ => false,
‘maxlength’ => 2,
‘defaultvalue’ => $guess_city,
‘headerinjectioncheck’ => ‘full’
));
‘defaultvalue’ will be the text between the or in the value= so the form will have pre-filled in data.
Thx for formbuilder – it is TOTALLY AWESOME
seems it removed html.
Let me restate a portion of what was above:
‘defaultvalue’ will be the text between the elements or in the value= so the form will have pre-filled in data.
Peeking @ the code I see a $field['defaultvalue'] mentioned. is this something that can be used to put in a ‘default value’ in a form? (Just being nosey.)
hi, may I know who to upload an image by using FormBuilder?
@Al – I’m afraid that isn’t currently possible.
Thanks Jonathan! I find Form Builder easy to use and to style – thanks for making it available to us, and thanks for the 1.5 version update. Much appreciated! =)
Hi everyone!
How i can add recaptcha.net, in this example?
Thank You for any help!
great tutorial…one question though when the form is submited it does not show the email From: in the header it just says “senders name”. Is there a way to show the senders email ? thanks
@dan You need to populate the emailResults function parameters with values submitted in your form, e.g.
$contactForm->emailResults(
‘you@yourdomain.com’,
$_POST['email'],
$_POST['name'],
‘Email subject’,
‘The following is an email sent by a visitor to mysite.com:’
);
$contactForm->emailResults(
‘you@yourdomain.com’, // The recipient (ie: you). Should ALWAYS be hard coded.
$_POST['email']
$_POST['name']
$_POST['subject']
);
how can I change this so that the senders email shows up in the “From” field
from: sender@sender.com
to: Don