home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

9.5. Redisplaying Forms with Preserved Information and Error Messages

9.5.3. Discussion

If your users encounter errors when filling out a long form, you can increase the overall usability of your form if you highlight exactly where the errors need to be fixed.

Consolidating all errors in a single array has many advantages. First, you can easily check if your validation process has located any items that need correction; just use count($errors). This method is easier than trying to keep track of this fact in a separate variable, especially if the flow is complex or spread out over multiple functions. Example 9-4 shows the pc_validate_form( ) validation function, which uses an $errors array.

Example 9-4. pc_validate_form( )

function pc_validate_form( ) {
  if (! pc_validate_zipcode($_POST['zipcode'])) {
     $errors['zipcode'] = "ZIP Codes are 5 numbers";
  }

  if (! pc_validate_email($_POST['email'])) {
     $errors['email'] = "Email addresses look like user@example.com";
  }

  return $errors;
}

This is clean code because all errors are stored in one variable. You can easily pass around the variable if you don't want it to live in the global scope.

Using the variable name as the key preserves the links between the field that caused the error and the actual error message itself. These links also make it easy to loop through items when displaying errors.

You can automate the repetitive task of printing the form; the pc_print_form() function in Example 9-5 shows how.

Example 9-5. pc_print_form( )

function pc_print_form($errors) {
    $fields = array('name'   => 'Name',
                    'rank'   => 'Rank', 
                    'serial' => 'Serial');

    if (count($errors)) { 
        echo 'Please correct the errors in the form below.';
    }

    echo '<table>';

    // print out the errors and form variables
    foreach ($fields as $field => $field_name) {
        // open row
        echo '<tr><td>';

        // print error
        if (!empty($errors[$field])) {
            echo $errors[$field];
        } else {
            echo '&nbsp;'; // to prevent odd looking tables
        }

        echo "</td><td>";

        // print name and input
        $value = isset($_REQUEST[$field]) ? 
                       htmlentities($_REQUEST[$field]) : '';

        echo "$field_name: ";
        echo "<input type=\"text\" name=\"$field\" value=\"$value\">";
        echo '</td></tr>';
    }

    echo '</table>';
}

The complex part of pc_print_form( ) comes from the $fields array. The key is the variable name; the value is the pretty display name. By defining them at the top of the function, you can create a loop and use foreach to iterate through the values; otherwise, you need three separate lines of identical code. This integrates with the variable name as a key in $errors, because you can find the error message inside the loop just by checking $errors[$field].

If you want to extend this example beyond input fields of type text, modify $fields to include more meta-information about your form fields:

$fields = array('name' => array('name' => 'Name', 'type' => 'text'),
                'rank' => array('name' => 'Rank', 'type' => 'password'),
                'serial' => array('name' => 'Serial', 'type' => 'hidden')
               );

9.5.4. See Also

Recipe 9.3 for simple form validation.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.