If you build many PHP based forms, you may find that there is quite a bit of duplication when it comes to their basic operation.
Because of this, I have created a form class which tries to abstract some of the boring bits... where each field is an object, bound to a single form object.
However, I should point out that it does not work perfectly on every project. As in, I have tried to use it a couple of times where it just over-complicated the code base.
Also, you might notice that the setup is quite verbose, this has been done to ensure that all developers can see what is going on. For example, if you are working in a team of programmers, and one of them is really a HTML developer, then it should still be trivial for them to make a field optional - without them distracting any other developers, or making silly mistakes.
Now an example of the field setup:
$form = new form();$fldName = new formFieldText($form, 'Name');$fldName->setMaxLength('Your name cannot be longer than XXX characters.', 250);$fldEmail = new formFieldEmail($form, 'Email');$fldEmail->setFormatError('Your email does not appear to be correct.');$fldEmail->setMinLength('Your email is required.', 1);$fldEmail->setMaxLength('Your email cannot be longer than XXX characters.', 250);
In this example, we have an optional 'name' field, which is limited to 250 characters. If I wanted to make it a required field, then I can call its setMinLength function, in the same way as the email field.
Due to its verbosity though, I would really recommend using TextMate with its tab triggers (examples and downloads).
And for those servers still running PHP4, you need to change the initialisation line to use a 'pass by reference' (=&)... for example:
$fldName =& new formFieldText($form, 'Name');Once the fields are setup, you can print them on the page with:
<div class="row<?= ($fldName->hasError() ? ' error' : '') ?>"> <span class="label"><?= $fldName->getHtmlLabel() ?></span> <span class="input"><?= $fldName->getHtmlField() ?></span></div>
And finally, to test if the form fields do not have any errors, its just a case of calling:
if (!$form->hasError()) { // Process}
Naturally, I would suggest using the source order explained on my PHP form setup article, as this is what the form class was built to work with.
If you think this script might be useful, you can download a copy of the source code, which contains instructions at the beginning on how to use it.
I also have some very basic documentation on the fields setup.
Thank you for looking at this code, any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.