Problem:- Display Inline Message in Form With Re-display Form
Solution:- Here we made two file to make a form to submit and show error message in inline and again to display same form to correct the information your user want to submit.
Contents
hide
Test.php
<style type="text/css"> .error{ color: red; } </style> <?php $flavors = array('', 'vanilla','Chocolate', 'Strawbery' ); $defaults = array('name'=> '', 'age'=>'', 'flavor'=> array()); foreach ($flavors as $flavor) { $defaults['flavor'][$flavor] = ''; } if ($_SERVER['REQUEST_METHOD']=='GET') { # code... $errors = array(); include __DIR__.'\show-form.php'; }else{ $errors = validateForm(); if (count($errors)) { if (isset($_POST['name'])) { $defaults['name'] = $_POST['name']; } if (isset($_POST['age'])) { $defaults['age']= "checked='checked'"; } foreach ($flavors as $flavor) { if (isset($_POST['flavor']) && ($_POST['flavor']==$flavor)) { $defaults['flavor'][$flavor] = "selected='selected'"; } } include __DIR__.'\show-form.php'; }else{ print "The form is submitted"; } } function validateForm(){ global $flavors; $errors = array(); if (!(isset($_POST['name']) && (strlen($_POST['name'])>3))) { $errors['name'] = "Enter a name of at least 3 letter"; } if (!isset($_POST['age'])) { # code... $_POST['age'] = 0; if (($_POST['age']!= '1')) { $errors['age'] = "Invalid age check box value"; } } if (empty($_POST['flavor'])) { $errors['flavor'] = "Choose a valid Flavor"; } return $errors; } ?>
show-form.php
<form method="post"> <dl> <dt>Your Name</dt> <?php if (isset($errors['name'])) {?> <dd class="error"><?php echo htmlentities($errors['name']); ?></dd> <?php } ?> <dd><input type="text" name="name" value="<?= htmlentities($defaults['name']); ?>"></dd> <dt>Are You Over 18 Year old</dt> <?php if (isset($errors['age'])) {?> <dd class="error"><?php echo htmlentities($errors['age']); ?></dd> <?php } ?> <dd><input type="checkbox" name="age" value='1' >Yes</dd> <dt>Your Fav Ice Cream Fav</dt> <?php if (isset($errors['flavor'])) {?> <dd class="error"><?php echo htmlentities($errors['flavor']); ?></dd> <?php } ?> <dd><select name="flavor"></dd> <?php foreach ($flavors as $flavor) {?> <option <?= isset($defaults['flavor'][$flavor])? $defaults['flavor'][$flavor]: ""; ?>> <?= htmlentities($flavor); ?></option> <?php } ?> </select> </dl> <input type="submit" value="Send Info" name=""> </form>
Output
इसे भी पढ़े – PDF फाइल का साइज कम कैसे करें?