Building a PHP 5 Form Processor: Coding the Form Generator Module

Most developers must deal with the job of developing robust data validation for forms on a regular basis. Nobody wants to write the same code over and over, so this article (the first of three in a series) will help you develop an extensible and reusable form validation package. By the end of the article, you will have all the relevant classes that integrate the generator module of the PHP form processor.

Introduction

As you’ll probably agree, one of the most common tasks during the development of a web application consists of writing checking code for validating user input, submitted by online forms. From a developer’s point of view, this might be sometimes an annoying activity, because it’s one of the things that you’re likely to do over and over again. Moreover, if you write and release an application which lacks form user data validation routines, sooner or later it will be broken up, due to the constant submission of erroneous data, either because of ignorance or maliciousness.

Considering that developing robust data validation is something that doesn’t bear discussion, and certainly is one of those jobs that most developers have to face very often, the best way to tackle the problem is either by picking up an existing validation library, or building in a reusable package. If you’re feeling inclined toward the first option, you can start using one of the numerous form checking libraries available on the Web. It’s just a few clicks away.

However, for those developers wanting to dive into the development of an extensible and reusable form validation package, this article might serve as an introductory process for developing and implementing an object-based form generation-verification solution. Since PHP supports creating classes in a very friendly way, in this first article I’ll walk through a step-by-step format to build some highly generic, customizable PHP 5 form generation classes. This first library of classes will comprise what I call a “generator” module, and allow you to programmatically construct (X)HTML forms, offering basic client-side validation features. Similarly, the second tutorial of this series will focus on developing a “validator” module, which will include a useful server-side validation class.

The end result of this experience will be a PHP 5 form processor, which can be customized with little difficulty, so it can work for you. Before I start coding the application’s first module, I’d like to state a few requirements: you’ll need to have an intermediate knowledge of object programming in PHP 5, as well as a basic familiarity with some of the PHP built-in data introspection functions.

With the formalities out of the way, let’s get started.

{mospagebreak title=Creating online forms: defining a reusable class for rendering form elements}

A good place to start coding the “generator” module is by defining a highly generic class, which can be capable of rendering programmatically form elements, and additionally integrating in a transparent way client-side validation routines. To meet all these requirements, I’ll begin defining the first class that composes the form processor, “formElement”. Its signature is shown below:

class formElement{
    private $html=”;
    public function __construct($type=’text’,$attributes=array
(‘name’=>’default’),$options=array()){
        // check for <input> elements
        if(preg_match(“/^
(text|radio|checkbox|password|hidden|submit|reset|button|image|
file)$/”,$type)){
            $openTag='<input type=”‘.$type.'” ‘;
            $closeChar=’ ‘;
            $closeTag=’/>';
        }
        // check for <textarea> and <select> elements
        else if(preg_match(“/^(textarea|select)$/”,$type)){
            $openTag='<‘.$type.’ ‘;
            $closeChar=’>';
            $closeTag='</’.$type.’>';
        }
        else{
            throw new Exception(‘Invalid element type’);
        }
        if(!is_array($attributes)||count($attributes)<1){
            throw new Exception(‘Invalid number of attributes for
<‘.type.’> element’);
        }
        // loop over element attributes
        $elemAttributes=”;
        foreach($attributes as $attribute=>$value){
            if(empty($attribute)||empty($value)){
                throw new Exception(‘Invalid attribute or value
for <‘.type.’> element’);
            }
            // check for ‘required’ attribute – add client-side
validation
            $attribute==’required’?JSGenerator::addValidation
($attributes
['name'],$value):$elemAttributes.=$attribute.’=”‘.$value.'” ‘;
        }
        // check for <select> options
        $selOptions=”;
        if(count($options)>0){
            foreach($options as $value=>$text){
                if(empty($value)||empty($text)){
                    throw new Exception(‘Invalid value or text
for <‘.type.’> element’);
                }
                $selOptions.='<option
value=”‘.$value.'”>’.$text.'</option>';
            }
        }
        // build form element(X)HTML output
        $this->html.=$openTag.trim
($elemAttributes).$closeChar.$selOptions.$closeTag;
    }
    // return complete (X)HTML
    public function getHTML(){
        return $this->html;
    }
}

Despite the seemingly complex structure of the above class, its rationale is fairly simple, so fear not. Essentially, what the class does is render programmatically form elements, according to the incoming parameters passed to its constructor. As you can see, this method accepts three arguments: first, the name of the element being rendered; second, an array containing the attributes of that element; and finally, an optional $options array, which will only be used to build the set of <option> tags, when a select box needs to be displayed.

Of course, the constructor does most of the hard work, since it takes care of generating dynamically the required (X)HTML markup, in accordance with the type of form element entered as argument. Internally, this method will create the corresponding code for each form control and append it to the overall output, represented through the $this->html property.

So far, the logic behind the class is fairly clear and shouldn’t be difficult for you to understand. According to the checking process performed by a few regular expressions, the class will construct a specific form element, by adding the pertinent attributes passed in as class parameters. However, as I said right at the beginning of this tutorial, my intention was to provide the “generator” module with some client-side validation features. With reference to this, take a look at the following piece of code:

// check for ‘required’ attribute – add client-side validation
     $attribute==’required’?JSGenerator::addValidation
($attributes['name'],$value):$elemAttributes.=$attribute.’=”‘.$value.'” ‘;

In short, what this line does is check for a “required” attribute, as part of the $attributes array. If this attribute is found, then a JavaScript checking snippet will be created on the fly by the “addValidation()” method, which, as you can see, belongs to the “JSGenerator” class. Are you wondering why I complicated the application by aggregating yet another class? Well, I decided to keep all the client-side validation routines encapsulated within a specific class, responsible for generating all the required JavaScript code.

As you can see, the methods of the “JSGenerator” class are used out of the object context — notice the use of the resolution scope operator (::) –- and originally this class was defined as abstract, so I didn’t have to concern myself too much with dealing with object instantiation. If this sounds rather confusing to you, don’t worry. In a few moments I’ll illustrate the functionality of this class.

Now, by returning to the “formElement” class, the remaining code speaks for itself. Note the definition of the “getHTML()” method, handy for fetching the (X)HTML markup of each form element:

public function getHTML(){
    return $this->html;
}

Hopefully you now understand how the “formElement” class works, so the next step in building the module for constructing forms will be showing the definition for the abstract “JSGenerator” class. All you have to do is scroll down the page and keep reading.

{mospagebreak title=Integrating client-side validation: defining the signature of the “JSGenerator” class}

As I explained before, the “JSGenerator” class takes care of loading the basic JavaScript validation functions, as well as the dynamic generation of the JavaScript code that uses these functions. First, let me show you how this class is defined and then I’ll demonstrate how it works. Its definition is as follows:

abstract class JSGenerator{
    private static $js=array();
    // load external JavaScript validating functions
    public function initializeFunctions(){
        self::$js['ext']='<script language=”javascript”
src=”functions.js”></script>';
    }
    // add JavaScript validating function to selected field
    public function addValidation($fieldName,$valData){
        if(!is_array($valData)){
            throw new Exception(‘Invalid client-side validation
array’);
        }
        $obj=’document.getElementsByTagName(“form”)[0].elements
["'.$fieldName.'"]‘;
        // obtain client-side validating function & error message
        list($valFunction,$errorMessage)=$valData;
        self::$js['int'].=’if
(!’.$valFunction.'(‘.$obj.’,”‘.$errorMessage.'”)){‘.$obj.’.focus
();return false};';
    }
    // return JavaScript code
    public function getCode(){
        return self::$js['ext'].'<script language=”javascript”>function validate(){‘.self::$js['int'].’}
</script>';
    }
}

Since I’ve already explained the reason for defining this class abstract, I’ll now focus on its job. As you can see, the class exposes only one static member, $js, which is declared by default as an array structure. This property will store first the whole set of JavaScript checking functions, and second the code responsible for calling these functions, in all the cases where form elements contain a “required” attribute.

According to the concepts deployed above, the first method of the class, “initializeFunctions()” is tasked with loading the JavaScript functions that perform basic client-side validation. Here’s what it looks like:

public function initializeFunctions(){
    self::$js['ext']='<script language=”javascript”
src=”functions.js”></script>';
}

In this case, I’m utilizing an associative array to identify each fragment of JavaScript code, thus the self::$js[‘ext’] element points to the external functions, while self::$js[‘int’], references all the internal code generated for required form fields. To clarify this concept, take a look at the method shown below:

public function addValidation($fieldName,$valData){
    if(!is_array($valData)){
        throw new Exception(‘Invalid client-side validation
array’);
    }
    $obj=’document.getElementsByTagName(“form”)[0].elements
["'.$fieldName.'"]‘;
    // obtain client-side validating function & error message
    list($valFunction,$errorMessage)=$valData;
    self::$js['int'].=’if
(!’.$valFunction.'(‘.$obj.’,”‘.$errorMessage.'”)){‘.$obj.’.focus
();return false};';
}

The above method takes two incoming parameters: the name of the field being validated, along with the $valData array. As you’ll see right at the moment of setting up an example, this array will contain the name of the JavaScript function used to check the field, in conjunction with the warning message displayed when validating the field. Of course, before I leap forward to reviewing the last class method, here is the list for the basic checking JavaScript functions used within the class:

function empty(obj,message){
    if(obj.value==”){
        alert(message);
        return false;
    }
    return true;
}
function int(obj,message){
    if(parseInt(obj.value)!=obj.value){
        alert(message);
        return false;
    }
    return true;
}
function email(obj,message){
    if(
!/.+@.+..+./.test(obj.value)){
        alert(message);
        return false;
    }
    return true;
}
if(document.getElementById&&document.createElement&&document.
getElementsByTagName){
    document.getElementsByTagName(‘form’)[0].onsubmit=function()
{return validate()};
}

So these functions take care of basic client-side validation. As you may have guessed, it’s fairly easy to add new functions as per your specific requirements, but for the moment I’ll keep the client-side checking process limited to validating empty fields, integer values and email addresses.

After the above functions have been loaded, the script will automatically invoke the “validate()” function when the form is submitted, so the checking functions in question can be conveniently utilized.

At this stage, the only class method left to explain is “getCode()”. Essentially, when called, it returns the complete JavaScript code that first loads the global functions, and then performs validation on all the required form fields. Its definition is as follows:

public function getCode(){
    return self::$js['ext'].'<script
language=”javascript”>function validate(){‘.self::$js['int'].’}
</script>';
}

At this point, hopefully you understand how the “JSGenerator” class does its business, by generating the complete client-side validating code. Therefore, join me in the new few lines, to see how the two classes defined earlier can be used in the context of a third class, in order to programmatically construct online forms.

{mospagebreak title=Constructing forms programmatically: defining the “formGenerator” class}

As a matter of fact, the two classes written above can’t do much on their own, if they’re not integrated within a new class that actually constructs web forms. Given this condition, I’ll write another additional class, which will be tasked with constructing programmatically the pertinent form. Its signature is shown below:

class formGenerator{
    private $html=array();
    private $action;
    private $method;
    public function __construct($action=”,$method=’post’){
        // setup form attributes
        $this->action=empty($action)?$_SERVER['PHP_SELF']:$action;
        $this->method=$method!=’post’||$method!
=’get’?’post':$method;
    }
    // add form element
    public function addElement($type=’text’,$attributes=array
(‘name’=>’default’),$options=array()){
        if(!$elem=new formElement($type,$attributes,$options)){
            throw new Exception(‘Failed to instantiate ‘.$type.’
object’);
        }
        $this->html[]=$elem->getHTML();
    }
    // add form part
    public function addFormPart($formPart='<br />’){
        $this->html[]=trim($formPart)==”?'<br />':$formPart;
    }
    // display form
    public function display(){
        $formOutput='<form action=”‘.$this->action.'”
method=”‘.$this->method.'”>';
        foreach($this->html as $html){
            $formOutput.=$html;
        }
        $formOutput.='</form>';
        // load global JavaScript checking functions
        JSGenerator::initializeFunctions();
        // append JavaScript code to general (X)HTML output
        $formOutput.=JSGenerator::getCode();
        return $formOutput;
    }
}

By studying the source code for the above class, it’s fairly easy to grasp its driving logic. Here, the “formGenerator” class behaves like a form element factory, which instantiates form objects and uses the features of polymorphism to fetch the corresponding (X)HTML markup of each of them (notice the use of the “getHTML()” method inside the class). In addition, the constructor performs some useful initialization tasks, such as setting up the values for the “action” and “method” properties of the form, and incidentally will assign default values to them if no parameters are passed to this method.

Now, after describing the initializing tasks of the constructor, turn your attention to the most relevant class methods. First, the “addElement()” method takes care of instantiating form objects, then calls their “getHTML()” method (again I strongly emphasize the use of polymorphism) and finally stores the returning (X)HTML code in the $this->html array. Definitely, this is an easy way to house progressively the markup code for the web form, as it’s being generated.

As you can see, the class also exposes the “addFormPart()” method, which comes in very handy for interspersing (X)HTML code within the form itself, and allows us to easily build the layout of form elements. Simple and efficient.

Finally, the last method of the class, “display()”, as its name suggests, will return the overall (X)HTML markup of the form, conjunctly with the JavaScript validation code, for being displayed directly on the browser. Of course, building the form’s markup is a fairly straightforward process because it’s only limited to iterating over the $this->html array and appending the JavaScript snippets, so understanding how this method works shouldn’t be a difficult thing.

At this stage, I’ve gone through the makings of the form generator module, which, as you’ve seen, is responsible for creating form elements and programmatically constructing online forms. Additionally, this module exposes some basic client-side validation features that can be easily customized, in order to fit specific requirements. Hopefully, this first tutorial has helped provide you with a clear idea of how a PHP 5 form processor can be developed with minor hassles.

Bottom line

That’s about it for the moment. Throughout this first article, I’ve written all the relevant classes that integrate the generator module of the PHP form processor. Using the nice OOP capabilities of PHP 5, coding a form processing library is actually an instructive experience, particularly if you’re pretty new to object programming.

In the second tutorial, I’ll be diving into writing the “validator” module, which, as you might guess, will expose a bunch of methods aimed at performing robust server-side validation on online forms. Meet you in the next tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan