Forum Moderators: coopster
How do you ensure that if you submit a form and there are errors, when you press the back button the text that you wrote will remain so only a few changes have to be made. Mine currently just wipes the whole slate clean!
I tried <? print $variablename;?>
As the initial value, had no effect though!
Thanks,
W.
I tried both your back buttons, but they done exactly the same as the browser back button!
The back button does not send the browser back instantly, it is as if the page has been reloaded.
Surely there is a way to make sure that the form is not automatically blanked out?
thanks,
W.
Book tutorials might suggest storing the form data as a session variable to make sure it's not lost. A much better way, though, is something on the lines of the following:
Create a php script which includes outputting an html form to the browser, which is self-referencing. That is, an 'action' attribute of phpself or "" (blank actually works best, especially if you want to preserve $_GET data as well as $_POST). When the form is submitted, it's sent to the same page. The script (before the html output) should include validation methods, creating an error (string or array) variable which should be appended to whenever a validation rule is broken. At the end of the validation rules, check if the array variable has data. If so, continue with the script (showing the form) and show the errors. The form elements should have a value of $_POST['var'] or something similar. That way you wouldn't lose your $_POST data. If the form data's valid, exit or redirect or whatever.
I use this for nearly all my web forms, and it works fine. Sample code would be:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
//start validating the form
if (empty($_POST['text_test'])) $errors[] = 'You didn\'t enter any text!';
//add more validation rules
//finished validating. check for errors
if (count($errors) > 0) {
//form invalid, show form again. implode form data for html output
$errors = '<p style="color:red">'.implode('', $errors).'</p>';
}
else {
//update database, write to file, output message, etc.
echo 'Thank you for a valid form!';
exit;
}
}
?>
<?=$errors?>
<form action="" method="POST">
enter some text: <input type="text" name="text_test" value="<?=$_POST['text_test']?>" />
<input type="submit" value="submit" />
</form>
[unchecked code!]
As you can see, the html output includes the contents of the 'errors' variable and the $_POST['text_test'] field in the relevant places. If there's no errors nothing will be shown, i.e. for the first time someone attempts to fill in the form. And the $_POST data for every HTTP request will be different, but populated by default with the contents of the previous request, so previous data is saved, and not lost.
This should help you out, I hope!
Cheers,
Alex ...