Re: Sessions?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Luc wrote:
Good morning list,
 I have my form up and running but something is missing: if you omit
 required fields, the form returns an error like:
 please fill in ...
 please fill in...

 the error message is displayed above the form on the same page. The
 problem is that upon showing the error message, the fields already
 filled out, return blank so that the user has to fill everything in
 again.

 What i would like to have is that the data already filled out, is
 being saved when the error message kicks in so that the user doesn't
 have to start al over again.


The way that i generally handle this is to use a class. I instantiate an object when the page loads, whether the form has been submitted or not. Then, if it has been, i populate the object's values with the data that's been posted, doing whatever validating that is required. Once that has all been taken care of, the script checks to see if the object has any errors set. If not, it then persists the data to the database (or whatever is required).

If there are errors, i display the form again. However, this time the object has values filled in. Thus, i can use form elements like so:

<input id="foo" name="foo" type="text"
  value="<?= $my_object->getFoo() ?>" />

Because i've instantiated the class even on the initial page load, the getFoo() method simply returns NULL the first time. Another benefit is that you can have default values for the class that the object will populate the form with.

Also, you can set the error messages in the class, so the object can display them at the proper place:

-- snip --
<?php
if ($my_object->hasError())
{
?>
  <p class="Error">There was an error with the submission. See below.</p>
<?php
}
?>

...

<fieldset>
  <legend>name</legend>

  <label for="first_name">first name</label>
  <input type="text" id="first_name" name="first_name"
    value="<?= $my_object->getFirstName() ?>" />

  <div class="Error"><?= $my_object->getError('first_name') ?></div>
</fieldset>

-- snip --

So, if the object's error array has something for the key 'first_name', an error is returned. If not, NULL is returned.

In any case, no session is required.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux