PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


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




Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: