In the past I thought my PHP and HTML Forms were set up so things were “sticky”, but I discovered last night that isn’t entirely the case.
If you fill out a Form and the values are valid, they “stick”, but if they are invalid they get erased. (I’ve been changing things around, and now forgot what is what…)
Here is what I have so far on my Private Message Form…
// *************************************************************
// HANDLE FORM. *
// *************************************************************
if ($_SERVER['REQUEST_METHOD']=='POST'){
// Form was Submitted (Post).
// Initialize Errors Array.
$errors = array();
// Trim all Form Data.
$trimmed = array_map('trim', $_POST);
// ************************
// Validate Form Data. *
// ************************
// Check Message.
if (empty($trimmed['pmBody'])){
// No Message.
$errors['pmBody'] = 'Enter a Message.';
}else{
// Message Exists.
// Check Message Length.
$pmLength = strlen($trimmed['pmBody']);
if ($pmLength > $maxLength){
// Invalid Message.
$errors['pmBody'] = "Message cannot exceed " . $maxLength . " characters. "
. "Your message is " . $pmLength . " characters.";
}else{
// Valid PM.
$pmBody = $trimmed['pmBody'];
}
}//End of CHECK MESSAGE
Notice this line above…
// Valid PM.
$pmBody = $trimmed[‘pmBody’];
Then down in my Form I have…
<!-- PM Body -->
<label for="pmBody">Message:</label>
<?php
echo '<textarea id="pmBody" name="pmBody" cols="65" rows="14">';
echo (isset($trimmed['pmBody']) ? htmlentities($trimmed['pmBody'], ENT_QUOTES) : '');
// echo (isset($pmBody) ? htmlentities($pmBody, ENT_QUOTES) : '');
echo "</textarea><br />\
\
";
if (!empty($errors['pmBody'])){
echo '<span class="error">' . $errors['pmBody'] . '</span>';
}
?>
If I recall correctly from last night, I replaced the commented out line above with this…
echo (isset($trimmed[‘pmBody’]) ? htmlentities($trimmed[‘pmBody’], ENT_QUOTES) : ‘’);
It almost seems like as soon as the Form is processed, I should assign each value in $trimmed[] to a variable AND THEN do my Form Validation, so that regardless of whether things pass or fail, my Form would be pointing to variables like $pmBody
Suggestions?
Thanks,
Debbie