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

Print Subscribe to PHP Subscribe to Newsletters

Getting Started with PHP's HTML_QuickForm

by Keith Edmunds
07/22/2004

I recently needed to develop an HTML form to input and edit contact details in a database with the usual name, address, telephone, and web page fields. This very common task is made more complex because of the need to validate the input data according to various rules and to notify the user if the validation process fails. I'm also always keen to separate the presentation logic (typically HTML) from the programming logic (PHP, in this case).

Enter PEAR, the PHP Extension and Application Repository, which provides an ever-growing number of classes to help with PHP programming. (See "An Introduction to PEAR" and "A Detailed Look at PEAR.") In this article, we will take a look at PEAR's HTML_QuickForm class.

A First Form

To start, I created a simple form with a heading, a text box, and submit and reset buttons, as follows:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html" 
    charset="UTF-8">
  <title>Testing PEAR HTML_QuickForm</title>
</head>
<body>
<?php
  require_once "HTML/QuickForm.php";

  $form = new HTML_QuickForm('frmTest', 'get');

  $form->addElement('header', 'hdrQuickformtest',
                    'QuickForm Example 1');
  $form->addElement('text',   'txtName',
                    'What is your name?');
  $form->addElement('reset',  'btnClear',
                    'Clear');
  $form->addElement('submit', 'btnSubmit',
                    'Submit');

  $form->display();
?>
</body>
</html>

Taking the PHP code line by line, the first line loads the class definitions for QuickForm.

Related Reading

Upgrading to PHP 5
By Adam Trachtenberg

Next, I instantiate an HTML_QuickForm object. This defines the name of the form (frmTest) and the method used to pass the form variables back to the PHP script (get, the alternative being post). By default, the form's action -- the URI to which to submit the form data -- is the same URI that displayed the form in the first place. This may seem unusual at first, but it is actually very useful, as we shall see.

The next four lines add four elements to the form. Elements are either orthodox HTML form elements, such as text boxes or radio buttons, or PEAR-specific pseudo-elements. The first parameter to the addElement method is mandatory; it defines the element type. Here, header is a pseudo-element that just places a heading bar on the form. The second parameter of each element is a name by which code can refer to it, if necessary. In the case of the header, the name is hdrQuickformtest. The third parameter is the text label associated with each element. For the header, this is the text to display. For the text element, a text box, it is the prompt before the text box. For the two buttons, it is the text on the button face.

Finally, the line $form->display(); renders the form to the screen.

When displayed, this page shows a header, a text box and two buttons: so far, so good. However, clicking the submit button appears to do nothing. The next step is to add the code to process the form after submission.

QuickForm Theory

HTML_QuickForm uses the concept of freezing elements of the form. The user cannot edit a frozen element. HTML_QuickForm enforces this by changing the rendering of the element. In the case of a frozen text box, the contents will render as simple text, thus denying the user the opportunity to edit the text value.

HTML_QuickForm also introduces the concept of validating a form. To validate, a form must have received one or more parameters via GET or POST, and all validation rules must succeed.

To test how freezing and validating work, I made a small change to the form by adding an if statement to call the form's validate method before displaying it. This will return true if the URI which called this code includes at least one POST/GET parameter, and all rules (of which there are none in this example) succeed. When this page first displays, there are no submitted parameters; validate returns false, and the form displays as before. The PHP code is:

<?php
  require_once "HTML/QuickForm.php";

  $form = new HTML_QuickForm('frmTest', 'get');
  $form->addElement('header', 'hdrQuickformtest',
                    'QuickForm Example 2');
  $form->addElement('text',   'txtName',
                    'What is your name?');
  $form->addElement('reset',  'btnClear',
                    'Clear');
  $form->addElement('submit', 'btnSubmit',
                    'Submit');

  if ($form->validate()) {
      # If the form validates then freeze the data
      $form->freeze();
  }
  $form->display();
?>

When a user clicks the Submit button, the action parameter of the form (by default, the URI that displayed the form in the first place) will now have a GET parameter appended in the form ?txtName=myname&btnSubmit=Submit. This means that the validation will succeed, freezing the form elements, which in turn means that the form will next render all elements in their non-editable forms.

Processing Results

This proved the basic operation of HTML_QuickForm, but I wanted to process the submitted data rather than just display it. This requires one additional method. For proof-of-concept purposes, I wrote a small function to display the data:

<?php
  require_once "HTML/QuickForm.php";

  $form = new HTML_QuickForm('frmTest', 'get');
  $form->addElement('header', 'hdrQuickformtest',
                    'QuickForm Example 3');
  $form->addElement('text',   'txtName',
                    'What is your name?');
  $form->addElement('reset',  'btnClear',
                    'Clear');
  $form->addElement('submit', 'btnSubmit',
                    'Submit');

  if ($form->validate()) {
    # If the form validates, freeze and process the data
    $form->freeze();
    $form->process("process_data", false);
  }
  else {
    $form->display();
  }

  function process_data ($values) {
    echo "<pre>";

    foreach ($values as $key=>$value) {
      echo $key."=".$value."<br>";
    }

    echo "</pre>";
  }
?>

In this example, the form will display only if the validation fails. When the validation succeeds, the process method defines which function to call. That function takes two parameters; the first is all of the submitted data in the form of an associative array. The second parameter to the process method, false, relates to uploaded files, so it does not apply in this case. In the above example, the process_data function merely deconstructs and displays the passed array, although in a production environment it would process the data as required.

Now I had a form that could solicit data from the user and pass it to another function for processing. However, this is nothing that an ordinary HTML form cannot do. The value of using PEAR's HTML_QuickForm comes with validating and applying automated filtering to the data, which is what I set out to do next.

Pages: 1, 2

Next Pagearrow




Recommended for You

Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

pear

Articles that share the tag pear:

The Dynamic Duo of PEAR::DB and Smarty (37 tags)

Programming eBay Web Services with PHP 5 and Services_Ebay (12 tags)

Three-Tier Development with PHP 5 (6 tags)

PHP's PEAR on Mac OS X (6 tags)

Caching PHP Programs with PEAR (6 tags)

View All

form

Articles that share the tag form:

PHP Form Handling (4 tags)

Getting Started with PHP's HTML_QuickForm (2 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

Sign up today to receive special discounts,
product alerts, and news from O'Reilly.
Privacy Policy >
View Sample Newsletter >
  • Youtube
  • http://www.youtube.com/OreillyMedia
  • Twitter
  • Subscribe
  • View All RSS Feeds >
O'Reilly Media

800-889-8969 or 707-827-7019
Monday-Friday 7:30am-5pm PT
©2011, O'Reilly Media, Inc.
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
  • About O'Reilly
  • Academic Solutions
  • Contacts
  • Customer Service
  • Careers
  • Press Room
  • Privacy Policy
  • Terms of Service
  • Writing for O'Reilly
  • Community
  • Authors
  • Forums
  • Membership
  • Newsletters
  • RSS Feeds
  • User Groups
  • More O'Reilly Sites
  • igniteshow.com
  • makerfaire.com
  • makezine.com
  • craftzine.com
  • labs.oreilly.com
  • Partner Sites
  • PayPal Developer Zone
  • O'Reilly Insights on Forbes.com