PHP
  Home arrow PHP arrow Page 4 - 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 - Constructing forms programmatically: defining the “formGenerator” class
    ( Page 4 of 4 )

    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!



     
     
    >>> 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