PHP
  Home arrow PHP arrow Page 3 - Building a PHP 5 Form Processor: Coding the Form Generator Module
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Building a PHP 5 Form Processor: Coding the Form Generator Module
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 28
    2006-01-16


    Table of Contents:
  • Building a PHP 5 Form Processor: Coding the Form Generator Module
  • Creating online forms: defining a reusable class for rendering form elements
  • Integrating client-side validation: defining the signature of the “JSGenerator” class
  • Constructing forms programmatically: defining the “formGenerator” class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Building a PHP 5 Form Processor: Coding the Form Generator Module - Integrating client-side validation: defining the signature of the “JSGenerator” class
    ( Page 3 of 4 )

    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.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek