The PHP Forms Class
The PHP Forms class is the last class out of 4 in the PHP Class series #1. So far we have been looking at a Database Class, a Paging Class and a Record Class and now it’s time to integrate and implement our Forms Class to get a good end on the first series. The reason for creating this PHP Forms Class is to make working with forms and validating forms a lot more fun and easy. We have a few goals we want the Forms Class to for fill:
- Extracting all form tags and attributes into our Forms class.
- Auto-generate a form based on a table in a MySQL database.
- Validate form fields using keywords such as letter, number, string, email, text and file.
- Add, edit and delete form fields from a form based on a table or built from scratch.
UPDATES: This walkthough is covering the basics of the PHP Form class. The download at the bottom of the page includes the very latest version which might be slightly different than the walkthough here!
Okay, looking a bit closer at our goals we see that the second goal is rather complex. If we manage to pull it off it will be really sweet. We need to handle normal form fields, text fields, file fields and select boxes, radio boxes and checkboxes. And all this needs to be auto-generate just using information from our MySQL database. We will work with three different pages: the one handling the Forms Class, the JavaScript handling the AJAX and the PHP validation script. Before we continue I want to tell you that none of these PHP classes is 100% correct or flawless. I’m posting them here to get input from you and share my ideas.
All 4 goals will be reach using 12 different functions and 7 private class variables and 1 static privatĀ variable. We start presenting the private class variables:
- $_fields: is a array containing all form fields
- $_method: is either ‘POST’ or ‘GET’, used when applying the <form> tag.
- $_action: contains the URL we should go to when the form is validated an submitted.
- $_id: each form we create will have a unique id, we can either provide one or it will get an auto-generate form id.
- $_db: holds and database instance.
- $_table: the name of a database table.
- $_validate: a boolean variable telling us to validate or not.
- $_numForms: the static private variable, counting how many forms we create.
The functions in the form.php file are:
- public __construct(): initializing our form object.
- public addField(): we use this to add a form field to our object.
- public getField(): returns the given form field.
- public setField(): updates a given form field.
- public setAttribute(): updates a attribute of a field in the form fields arra.
- public removeField(): removes a given form field.
- public generate(): generates a form from a specific MySQL database table.
- private createField(): creates the actual html markup
- private createLabel(): help function to createField(), generates a label.
- pubic validate(): makes it possible to turn off the validation script.
- public create(): sets everything together.
- public view(): used for debug.
Starting with the __construct() function we are required to supply at least 2 parameters: $method and $action. They have the same task as in normal HTML markup, the $method decide if we should use ‘GET’ or ‘POST’. The $action let us know where we are suppose to go when the form is valid and submitted. Then we are able to supply a third parameter in a array. The array can have an ‘id’, ‘db’ and ‘table’ key. Even though the Form Class gives a unique id to every form we create we might want to supply our own id, this is done here. As for the ‘db’ and ‘table’ key, these are used when we want to auto generate a form using the generate() function. Since the third parameter is optional we don’t need to supple a ‘db’ and ‘table’ to be able to create a form from scratch. At the very end of the function we create a $_SESSION which we will use when we validate. The main task of the function is to assign our private class variables with the incoming parameters. We are using static class functions from the Common Class.
Next, public addField(). The function takes 3 parameters, 2 required, 1 optional. The required once are $name, $type and the optional $attributes.
- $name: the name of the field.
- $type: which type the field should be. (text, password, textarea, select, radio, checkbox)
- $attributes: a vast list of key => value entries in an array. Each one will be described in the validation presentation.
The function assigns new fields into our class variable $_fields. If we find a field with the type = file we change the private variable $method to post. The $attribute parameter is the magic parameter holding all information regarding validation. We check if we want to show labels and if we find any ’snippets’. A snippet is a piece of code we want to add after the field.
Next four functions are rather easy and self-telling. We use these functions to manipulate fields already added in the privateĀ $_fields variable, which were created from our auto-generate function. We might want to remove fields, edit field values or validation rules, look at a field and more. The functions I’m talking about is getField(), setField(), setAttribute() and removeField(). We just make sure the parameter, $key, is found in our private $_fields array. The $key must be the name of the field.
This next public function is a rather large one, but not that complicated. The generate() function is the function making this Form Class interesting. The function takes 1 optional parameters: $attributes. The $attributes parameter is an array of default values and default validation rules. The first thing we do is to see that we have added a database object and a table to work on. After that we gather information from both the mysql_fetch_field method and by using the ‘SHOW COLUMNS’ query command. This is because we want to know two important things:
- When we encounter a blob, we need to know if it is of data type text or a file. This can’t be done just using mysql_fetch_field.
- When we encounter a enum, we want to be able to get all values in a nice radio link. This can’t either be done just using mysql_fetch_field.
The two ways of getting information about a MySQL field is sometime overlaying each other, meaning we get the same information twice, at least we are able to fetch the same information from both techniques. Sadly non of them alone is supplying enought information, therefore we use both techniques.
Inside the for-loop we are able to set validations rules to each field depending on the data type of the field in the database. The validation rules are these: required, format, min, max, label, showLabel, boxClass, fieldClass and snippet. This means we can set a max value and a min value. We are able to see if the field is required or optional and set a validation rule for that. Each field will get a ‘format’ rule depending on the data type. If the name of the field is ‘email’ or ‘password’ we use special format validation rules. We can supply a class for the form field and a box class for the div around each form field. At the very end we add each field to our private $_field array using the addField() function. Basically this function takes one field at a time found in the supplied MySQL database table. We gather as much information as possible about the field and then make desicions about which validation rules the field should get. When we are done we add it to the private $_fields variable.
Puew, that’s a long function but each line is small and simple. The next function, createField() is also a long function but a very simple one. The function will create a correct label and form field with the HTML markup code. We will look at the field and see if the field type matches anything of: text, password, hidden, file, radio, checkbox, textarea, select or submit. If it does we create the HTML markup code. Together with this function we use createLabel(), it will create the label for the field and it’s used as a help function to createField(). The code itself is not that complicated so I will not describe it any further, it’s just made up of if/elseif to find the correct field type.
The next three functions are similar the ones found in the Database Class and the Paging Class. The first one is validate(), with this you are able to turn of the validating script when setting the incoming parameter to false, the validating script is true as default.
The create() function will gather all the information about the fields we have provided and finally end up adding the form tags making it possible to echo out the result as a working form with correct and valid syntax. Lastly we have the view() function which is used when we want to debug our form, we are able to see which fields we have, the validation rules, values and much more.
Okay, we are done with the first part of the Form Class We have presented the actual Form class. With this we are able to write a form using this syntax:
We create our form object with the two required parameters ‘GET’, ‘default.php’ as $method and $action. We add two fields named ‘username’ and ‘password’, each with ‘text’ as type for ‘username’ and ‘password as type for the ‘password’ field. Then we add the validation rules with different formats, both fields are required and the minium length of the field must be 3 chars long. Lastly we add the ’submit’ button.
This next example will show two new things. We will fetch values using our Record Class from a user, we will use the get_values() from the Record class. Secondly we will auto generate the the same form we did in example one. We will add a ‘db’ and a ‘table’ key where we create our object. We will then add the values we fetched from our user to our generate() function and the username field will get a default value (password will be empty because that field is empty in the database).
Both example results is shown here:
Okay, so there we have it. This is the Form Class part 1. Coming up is the JavaScript file and the validation PHP page. You might wonder why we will use a PHP page to validate our fields, this is only because we have the Form class containing our fields which we are going to validate.
You can download the full PHP source code of the Forms Class right here:
About this entry
You’re currently reading “The PHP Forms Class,” an entry on Is the coffee still warm?
- Published:
- June 25, 2008 / 7:02 am
- Category:
- June
- Tags:
- attributes, auto generate, blobs, checkbox, class, example, field, form, forms, mysql, mysql database, oop, php, php programming, results, select, submit, tags, textarea, validate, __construct








No comments yet
Jump to comment form | comments rss [?] | trackback uri [?]