Jump to content

Re-populate form fields if error.


Scooby08

Recommended Posts

Say I have a form in a file called form.php.. The action on that form is process.php.. process.php validates for errors and sends the message back to form.php if errors.. I don't know how to repopulate the form values that were entered so they don't have to start over again when errors occur.. If the form were submitted to itself I could use $_POST['field_info'], but since it goes to process.php first I lose that $POST.. How do I get that info to carry back over?? I do have sessions going as well, but am not sure how or if I can use them to my advantage on this one..

 

Can anybody give me some pointers??

Link to comment
https://forums.phpfreaks.com/topic/124125-re-populate-form-fields-if-error/
Share on other sites

Here are a couple functions I use to do this exact thing.

<?php

function errorCheck($field)
{
if(isset($field) && $field != '')
{
	$value = 'value="'.$field.'"';
	echo $value;
}
}


?>

To use it

<input class="textbox" name="zip" <?php errorCheck($zip); ?> type="text"  id="zip"  size="10" maxlength="5" />  

Put the form and the processing on the same page, it makes it much easier to deal with.

<?php 

if(isset($_POST['SubmitForm']))
{
   //process form now
   // because it has been submitted
}
else
{
   // show the form 
  // it has not been submitted.
}
?>

 

or

 

<?php
if(isset($_POST['SubmitForm']))
{
   //process form now
   // because it has been submitted
}
?>
<form name="theForm" id="theForm" action="<?php $_SERVER['PHP_SELF']; ?>" />
the form goes here.....

</form>

 

One option is to put the form into a function so you can call it in the proper places, otherwise just have the form processing sitting in the top without the else{ } part. You can then deal with the form and do what you need to do with it, and set an array to hold the errors. e.g.

 

$error['username'] = 'Please enter a username';

 

then you can loop through the errors and display them.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.