The PHP Form Class: One becomes two
The PHP Form Class has been useful in many situations and judging by the stats here on the blog you guys seem to like it also. After using it projects I have noticed one annoying thing: it’s very hard to get the design and layout the way you want. The code from generating the form wasn’t clear and nice. In fact the code was harder and much uglier than if we had written a form using just HTML.
How can we improve this? Simple, we remove all field attributes concerning layout except for the fieldClass (we rename it to class) and we make it possible to print out each field individually. This means that we will be able to control our layout much easier with DIV and CSS elements. We could do this before but now we extract the design element from the PHP Form Class into the HTML/PHP page we are working, making the PHP Form Class nicer and the work processes smoother and much more simple. To make the PHP Form Class even more specific to it’s task we will remove all methods handling the auto generation. The auto generation methods will go into their own PHP class called The PHP AutoForm Class which will be available in a near futur.
The field attributes
Instead of going through the actual code behind the PHP Form Class I will go through how we can use it, the methods and design ideas we are aiming for. The very first thing we need to do is to create our form object. The constructor method takes two parameters: a method (post or get) and a action, these two are required. We are able to supply a third parameter, a name. This will be the name of the form, if we don’t supply a name, a name will be given for us.
$form = new Form('get', 'index.php');
To add a field to our form we use the addField method:
$form->addField('username', 'text');
The above code snippet is the required information we need to add to our addField method. The first parameter is the name of the field and the second the field type. In this case we named our form field to username and it will be a text field. If we want we can leave it this way or add more options as a third parameter inform of a array. The following attributes can be added to a field:
label
If label is not set, the name of the field will be set as the field label.showLabel
If set to false the field label will be removed.class
CSS class the field will apply.value
Default value / checkbox, radio and select optionsvalidate
Set to true the field is validated, set to false the field is not.format
Field format. Possible values are:
- text (all possibile characters found in a standard article)
- string (a-z, A-Z, ., ?, ‘, “, -, +,:,/,\,(,))
- char (a-z, A-Z)
- integer (0-9)
- custom (see further down)required
Set to true the field is required, set to false the field is not required.min
Minimum chars or selected checkboxes/selections.max
Maximum chars or selected checkboxes/selections.
This means we can rewrite the code before and add a required and min attribute to the field. Example:
$form->addField('username', 'text', array('required'=>true, 'min'=>3));
Now we are saying: Add a new field named ‘username’ with the type ‘text’. The field is required and the minimum chars required for the field is 3. So, to make the validation valid we need to enter something in this ‘username’ field and that something must be at least 3 chars in length. Notice how the third parameter is a array, the addField method only takes three parameters, all extra attributes must be added into this array.
The field types
Now when we now how to add field attributes to a field we are going to look at the different field types we can use, you will probably recognize them:
- text
- textarea
- checkbox
- radio
- select
- hidden
- submit
- image
- password
How can we create a number of checkboxes ranging from 1-5 where 3 and 4 are selected? We also need to make the field required and you can only select 4 checkboxes maximum. We try:
$form->addField('boxes', 'checkbox', array('value'=>array('1'=>false, '2'=>false, '3'=>true, '4'=>true, '5'=>false), 'required'=>true, 'max'=>4));
The only weird looking thing here might be the value attribute. The value is pointing to another array of key/value pairs. If you look closely it’s not that weird. We are creating a new field named ‘boxes’ with the type ‘checkbox’. The field has 5 different values to plot out namely our 1-5 checkboxes we wanted to print out. Number 3 and 4 had to be selected in the beginning, we simple did this by setting the value to true for those specific key/value pairs. Lastly we added the ‘required’ and ‘max’ attributes. When we are dealing with fields with multiply values such as checkboxes, radios and selects the values must be added as a array and don’t forget the attribute name is ‘value’ not ‘values’. This is because for text and textarea we are talking about the default value of the field.
To add a default value to a text field we simple write:
$form->addField('username', 'text', array('value'=>'Your username'));
Before we move on I will also take a example with the format attribute. With this attribute you can be sure that the user doesn’t provide any illegal chars into your fields, at least the field will not be valid. As I mentioned before you can provide a custom format rule. This rule is added as a extra field attribute and must be named ‘custom’ and point to your custom rule. At the moment you are able to enter a X for a character, Z for integers, _ for space and a character matching that exact char. That means, if we write XXX_ZZZ-ZZZ the rule will try to match 3 characters followed by a space, followed by 3 integers, followed by a – followed by 3 integers. Another example, we write MOO-XXX the value of the field must match MOO exactly followed by a – followed by 3 characters.
The form in action
So far we have discussed the attributes and types of the fields. Now we will take a look on how we can print the form and fields on our screen. After all, the main reason for updating the PHP Form Class was to extract the design element.
We take it from the beginning so we don’t mess anything up. The PHP Form Class package includes 5 different pages: Form.class.php, validate.js, validate.php, jquery.js and finally our help class Common.class.php. If you already have jQuery on your site you don’t need to include the jQuery.js file found here. In our index.php page we start coding:
<?php
include('Common.class.php');
include('Form.class.php');
session_start();
?>
It is important that we don’t forget the session_start() line because the validation of the form is using sessions. When we have our Form class included we create our form object and our fields.
<?php
$form = new Form('get', 'index.php');
$form->addField('username', 'text', array('required'=>true, 'min'=>3, 'format'='string'));
$form->addField('password', 'password', array('required'=>true, 'min'=>3));
$form->addField('submit', 'submit', array('value'=>'Login'));
?>
This is a simple form, a login form. We first add our ‘username’ field which is a text field. It is required and the format must be string and the input must be atleast 3 chars long. Next we add a password field, also required and the input must be atleast 3 chars long. Lastly we create a submit button with the value ‘Login’.
Notice that we didn’t include any design elements here. If we want we can print out the whole form using the printForm() method. This method is violating our rule ‘remove all design element’. It takes one parameter, a class. This class will be applied, if set, to a div element surrounding each field. This will be useful because when if we just want to print each field after each other it can come in handy to be able to fix the final adjustments with a CSS class. The printForm() method will, as I said, print out the form header, each field and finally the form end.
<?php
echo $form->printForm();
?>
With the printForm() method we are not able to decide in detail where each field should be placed. To do that we use the printField() method. This method takes a field name as it’s parameter. If we want to print out our ‘username’ field found in our login form we simple print:
<?php
echo $form->printField('username');
?>
This freedom also comes with a price. When we used the printForm() method we know that the whole form should be printed and therefore we could print the form header and form end. When we use the printField() method we must first call the printHeader() method and when we are done with all fields we need to apply the printClose() method. If we don’t do this the form will not be valid. You cannot use both printForm() and printField() because it will print the same form making the id’s not unique.
There we have it. I think that’s a good start if you are planning on using this PHP/jQuery/Form/Validation script. As for validation we still use the jQuery script we wrote before, slightly updated. In my next post we will look at the new method validate() found in our Form class which will validate the fields without any JavaScript. Until then, make sure to check out:
About this entry
You’re currently reading “The PHP Form Class: One becomes two,” an entry on Is the coffee still warm?
- Published:
- September 4, 2008 / 9:49 am
- Category:
- September
10 Comments
Jump to comment form | comments rss [?] | trackback uri [?]