PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 9.5 Redisplaying Forms with Preserved Information and Error Messages

9.5.1 Problem

When there's a problem with data entered in a form, you want to print out error messages alongside the problem fields, instead of a generic error message at the top of the form. You also want to preserve the values the user typed into the form the first time.

9.5.2 Solution

Use an array, $errors, and store your messages in the array indexed by the name of the field.

if (! pc_validate_zipcode($_REQUEST['zipcode'])) {
    $errors['zipcode'] = "This is is a bad ZIP Code. ZIP Codes must "
                       . "have 5 numbers and no letters.";
}

When you redisplay the form, you can display each error by its field and include the original value in the field:

echo $errors['zipcode'];
$value = isset($_REQUEST['zipcode']) ?
               htmlentities($_REQUEST['zipcode']) : '';
echo "<input type=\"text\" name=\"zipcode\" value=\"$value\">";

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.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    9.1 Introduction
    Recipe 9.2 Processing Form Input
    Recipe 9.3 Validating Form Input
    Recipe 9.4 Working with Multipage Forms
    Recipe 9.5 Redisplaying Forms with Preserved Information and Error Messages
    Recipe 9.6 Guarding Against Multiple Submission of the Same Form
    Recipe 9.7 Processing Uploaded Files
    Recipe 9.8 Securing PHP's Form Processing
    Recipe 9.9 Escaping Control Characters from User Data
    Recipe 9.10 Handling Remote Variables with Periods in Their Names
    Recipe 9.11 Using Form Elements with Multiple Options
    Recipe 9.12 Creating Dropdown Menus Based on the Current Date
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele