PHP
  Home arrow PHP arrow Page 4 - Building a PHP 5 Form Processor: Codin...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

Building a PHP 5 Form Processor: Coding the Form Generator Module
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 26
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · The first article walks through the development of the different classes that...
       · Not that I'm lazy (just don't have the time right now), but is there a code archive...
       · I'd like to thank you for your kind comments on this article. I really appreciate...
       · Can you give some exmples of how to use these classes, please
       · Hello,Thanks for the feedback. If you want to see a full-featured example on how...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT