On my website I have plenty of form and fields, I have a system that works perfectly but is really painful and to get up and running.
This is what my system does, once you send the form all the info is sent to a class which possesses all the data and validates it. It also stores the value of the field like this $_SESSION['userUpdate']['firstName'][1] = $firstName;
If there is an error it creates a session variable like this $_SESSION['userUpdate']['firstName'][0] = 1;
the 1 tells that the field was empty. If there is no error the session variable would be at 0.
If no errors where found in the validation process the data is sent to the database.
After that the form page is reloaded with :
header( 'HTTP/1.1 303 See Other' );
header( 'Location: '.curPageURL().'' );
I use that so that you cannot resend the data when reloading the page. That is the reason I'm using all these session variables.
Then with a lot of it/else if/else I check the values of the session variables and output errors and also populate the form with the data entered previously.
Let me show you an example for a firstname field.
This is the HTML code :
<label for="firstName" class="block">First Name</label>
<span>Your first name goes here.</span><?php echo $text_first_name ?>
<input type="text" id="firstName" class="mediaText" name="firstName" value="<?php echo $first_name2; ?>" onchange="needToConfirm=true" <?php echo $style_first_name ?> />
This is the validation process by the class :
$_SESSION['ui']['first_name'][1] = $this->first_name;
if (isset($this->first_name))
{
if($this->first_name == NULL)
{
$_SESSION['ui']['first_name'][0] = 1;
}
else if(minRange(3, $this->first_name))
{
$_SESSION['ui']['first_name'][0] = 2;
}
else
{
array_push($set, "FirstName = '".$db->sql_escape($this->first_name)."'");
}
}
This is the php code that handles the eventual errors :
$error_bg = "style=\"background:#EE5C42\"";
//FIRST NAME
if($_SESSION['ui']['first_name'][0] == 1)
{
$style_first_name = $error_bg;
$first_name2 = $_SESSION['ui']['first_name'][1];
}
else if($_SESSION['ui']['first_name'][0] == 2)
{
$style_first_name = $error_bg;
$first_name2 = $_SESSION['ui']['first_name'][1];
$text_first_name = "<span class=\"errorText\">Your first name must consist of at least 3 characters.</span>";
}
else
{
$first_name2 = $userdetails["FirstName"];
}
At the end of the page there is a little function to unset the session variables.
I am wondering it there is any way to make this simpler and easier to get up and running ?