Form values should not clear
I have a form to submit my contact info. and i'm fetching form fields using php like:
if(isset($_post开发者_如何转开发['submit']))
{
//submit cantact info
}
else
{
//bad user
}
my problem is: if the user is failed to submit form the "form values should not clear"....
but form values are clearing on click submit button..! so anyone know how to prevent clear form values?
you have to populate these fields manually.
the general idea stands for using POST/Redirect/GET method
after receiving POST data you have to check it and raise error flag
and in case of some errors you have to show the same form back, with filled inputs and corresponding error messages.
here is a rough example:
<?
$err = array();
if ($_SERVER['REQUEST_METHOD']=='POST') {
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
and then in the form.tpl.php template make it like this:
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
You have to (manually) put the submitted values in the form elements. Example:
<input type="text" name="username" value="<?=( isset( $_POST['username'] ) ? $_POST['username'] : '' )?>" />
You need to keep track of the form values. One suggestion is to setup an array of default values that is used when presenting the form markup.
On POST, you then merge the post data. For example
$formData = array(
'foo' => '',
'bar' => 'default value',
'baz' => ''
);
if ('POST' == $_SERVER['REQUEST_METHOD') {
$formData = array_merge($formData, $_POST);
// do validation, handle success
}
Then, in HTML
<input name="foo" value="<?php echo htmlspecialchars($formData['foo']) ?>">
<!-- etc -->
精彩评论