PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

Quick and Clean PHP Forms
Pages: 1, 2, 3

The Complete Implementation

At this point, it should be clear that these new wrapper functions could be logically implemented within a subclass of HTML_QuickForm, that would in turn make the contact form code cleaner still. The subclass, called HTML_QuickerForm, is implemented in a file of the same name:



  require_once('HTML/QuickForm.php');
  
  class HTML_QuickerForm extends HTML_QuickForm {
  
    function HTML_QuickerForm($formName='', 
                              $method='post', 
                              $action='', 
                              $target='', 
                              $attributes=null, 
                              $trackSubmit = false) {
       parent::HTML_QuickForm($formName, 
                              $method, 
                              $action, 
                              $target, 
                              $attributes, 
                              $trackSubmit);
       $this->applyFilter('__ALL__', 'trim');
     }
        
    function addDefaultMessages($default_messages) {
      $this->default_messages = $default_messages;
    }
    
    // replaces underscores with spaces 
    // and capitalizes the resulting words
    function createFieldLabel($field_name) {
      return ucwords(ereg_replace('[_]', ' ', $field_name));
    }
    
    function addQuickRules($field_name, 
                           $validation_methods) {
      if ($validation_methods != '') {
        $methods = split(',', $validation_methods);
        foreach ($methods as $method) {
          $validation_message = sprintf($this->default_messages[$method], ereg_replace('[_]', ' ', $field_name));
          $this->addRule($field_name, 
                         $validation_message, 
                         $method);
        }
      }                  
    }
    
    function addQuickElement($field_name, 
                             $field_type, 
                             $validation_methods='', 
                             $attributes='') {
      $this->addElement($field_type, 
                        $field_name, 
                        $this->createFieldLabel($field_name), 
                        $attributes);
      $this->addQuickRules($field_name, 
                           $validation_methods);
    }
    
    function executeForm() {    
      if ($this->validate()) {
        $this->process("process_data", false);
      } else {
        $this->display();
      }
    }
  
  }

First, notice that the constructor has been overridden to automatically apply the trim filter to all form fields by default, a best practice learned from Keith Edmunds' tutorial. The $default_messages variable is now an instance variable instead of a global, and I renamed the functions so that, as methods of this subclass, they will not override the similarly named existing implementations in the super class they were meant to wrap. I also added the ability to add attributes to form elements to round out the functionality.

Further subclasses could be defined for common implementations of the process method callback. Since emailing the validated form data is a typical requirement of contact forms, this can be implemented in a subclass of HTML_QuickerForm with a small amount of PHP reflection trickery:

class HTML_QuickMailForm extends HTML_QuickerForm {
    function executeForm() {    
    if ($this->validate()) {
      $this->process(array(get_class($this), 'process_data'), false);
    } else {
      $this->display();
    }
  }
  
  function process_data($values) {
      require_once "emailHelper.php";
      emailValues($values);
  }
}

The email contact form can now be rewritten in a way that succinctly specifies only what is necessary for this particular form implementation:

Example 2.

require_once('HTML_QuickerForm.php');
$form = new HTML_QuickMailForm('contact_form', 'post');

$default_messages = array ('required' => 'Please enter your %s.',
                            'email'    => 'Please enter a valid %s.'
                          );
$form->addDefaultMessages($default_messages);

$form->addQuickElement('name',          'text',     'required',      'class=name'); 
$form->addQuickElement('address',       'text'      ); 
$form->addQuickElement('email_address', 'text',     'required,email'); 
$form->addQuickElement('home_phone',    'text',     'required'      );
$form->addQuickElement('cell_phone',    'text'      ); 
$form->addQuickElement('subject',       'text'      ); 

$textareaAttributes = array("wrap" => "virtual", 
                            "cols" => "60"
                            );
                            
$form->addQuickElement('message',       'textarea', '', $textareaAttributes); 
$form->addQuickElement('submit',        'submit'    ); 
$form->executeForm();

This version of the contact form actually contains more functionality, because more validations have been added, as have element attributes, for the sake of giving a more complete example of how to use the new subclass. For a given form element, multiple validation methods can be specified using comma separated strings, as shown by the email_address field, and multiple attributes can be specified using an array of appropriate values, as shown by the message field. In each case, single strings can also be used when only one value is needed, as shown by the name field which specifies only one validation method and one attribute.

Thanks to the power of HTML_QuickForm, and a little time spent personalizing how it may be used typically, this is all the coding needed to create an email contact form in the future.

Pages: 1, 2, 3

Next Pagearrow




Recommended for You

  1. Cover of Programming PHP
    Programming PHP
    Print: $39.95
  2. Cover of Mastering Regular Expressions
    Mastering Regular Expressions
    Print: $44.99
    Ebook: $35.99
  3. Cover of Web Database Applications with PHP and MySQL
    Web Database Applications with PHP and MySQL
    Print: $44.95
    Ebook: $35.99
  4. Cover of PHP Pocket Reference
    PHP Pocket Reference
    Print: $9.95

Tagged Articles

Be the first to post this article to del.icio.us

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com