Recipe 9.12. Redisplaying Forms with Inline Error Messages


9.12.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 entered in the form, so they don't have to redo the entire thing.

9.12.2. Solution

As you validate, keep track of form errors in an array keyed by element name. Then, when it's time to display the form, print the appropriate error message next to each element. To preserve user input, use the appropriate HTML idiom: a value attribute (with entity encoding) for most <input/> elements, a checked='checked' attribute for radio buttons and checkboxes, and a selected='selected' attribute on <option/> elements in drop-down menus. Example 9-22 displays and validates a form with a text box, a checkbox, and a drop-down menu.

Redisplaying a form with error messages and preserved input

<?php // Set up some options for the drop-down menu $flavors = array('Vanilla','Chocolate','Rhinoceros'); if ($_SERVER['REQUEST_METHOD'] == 'GET') {     // Just display the form if the request is a GET     display_form(array()); } else {     // The request is a POST, so validate the form     $errors = validate_form();     if (count($errors)) {         // If there were errors, redisplay the form with the errors         display_form($errors);     } else {         // The form data was valid, so congratulate the user         print 'The form is submitted!';     } } function display_form($errors) {     global $flavors;     // Set up defaults     $defaults['name'] = isset($_POST['name']) ? htmlentities($_POST['name']) : '';     $defaults['age'] = isset($_POST['age']) ? "checked='checked'" : '';     foreach ($flavors as $flavor) {         if (isset($_POST['flavor']) && ($_POST['flavor'] == $flavor)) {             $defaults['flavor'][$flavor] = "selected='selected'";         } else {             $defaults['flavor'][$flavor] = '';         }     }     ?> <form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'> <dl> <dt>Your Name:</dt> <?php print_error('name', $errors) ?> <dd><input type='text' name='name' value='<?php echo $defaults['name'] ?>'/></dd> <dt>Are you over 18 years old?</dt> <?php print_error('age', $errors) ?> <dd><input type='checkbox' name='age' value='1' <?php echo $defaults['age'] ?>/> Yes</dd> <dt>Your favorite ice cream flavor:</dt> <?php print_error('flavor', $errors) ?> <dd><select name='flavor'> <?php foreach ($flavors as $flavor) {     echo "<option {$defaults['flavor'][$flavor]}>$flavor</option>"; } ?> </select></dd> </dl> <input type='submit' value='Send Info'/> </form> <?php } // A helper function to make generating the HTML for an error message easier function print_error($key, $errors) {     if (isset($errors[$key])) {         print "<dd class='error'>{$errors[$key]}</dd>";     } } function validate_form() {     global $flavors;     // Start out with no errors     $errors = array();     // name is required and must be at least 3 characters     if (! (isset($_POST['name']) && (strlen($_POST['name']) > 3))) {         $errors['name'] = 'Enter a name of at least 3 letters';     }     if (isset($_POST['age']) && ($_POST['age'] != '1')) {         $errors['age'] = 'Invalid age checkbox value.';     }     // flavor is optional but if submitted must be in $flavors     if (isset($_POST['flavor']) && (! in_array($_POST['flavor'], $flavors))) {         $errors['flavor'] = 'Choose a valid flavor.';     }     return $errors; } ?>

9.12.3. Discussion

When a form is submitted with invalid data, it's more pleasant for the user if the form is redisplayed with error messages in appropriate places rather than a generic "the form is invalid" message at the top of the form. The validate_form( ) function in Example 9-22 builds up an array of error messages that display_form( ) uses to print the messages in the right places.

Extending Example 9-22 is a matter of expanding the checks in validate_form( ) to handle the appropriate validation needs of your form and including the correct HTML generation in display_form( ) so that the form includes the input elements you want.

9.12.4. See Also

Recipes 9.2 to 9.9 for various form validation strategies.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net