Setting Form Values to Previously Entered Values

This is a discussion on "Setting Form Values to Previously Entered Values" within the PHP Forum section. This forum, and the thread "Setting Form Values to Previously Entered Values are both part of the Program Your Website category.



Go Back   Webforumz.com > Main Forums > Program Your Website > PHP Forum

Notices


Reply
 
LinkBack Thread Tools
  #1 (permalink)  
Old Oct 6th, 2006, 17:08
masonbarge's Avatar
Highly Reputable Member
Join Date: Jan 2006
Location: Atlanta GA
Posts: 631
Thanks: 0
Thanked 0 Times in 0 Posts
Setting Form Values to Previously Entered Values

I'm sure a lot of developers know this, but still I invented it from scratch and thought I'd share it.

The problem is that, when you fill out a form and it is rejected for whatever reason, you don't want to make the user fill out the entire form again. You can use php to retain all the entered values when the form is rejected - usually because one box is not filled out, or doesn't meet the regular expression values, but also when the server is slow/down, whatever.

I've left out all validation (although afaik the only low-level danger in a POST method form is the text box, which in the example gets a simple 2 or 3 numeral validation. ).

The text box (or text) is easiest (I got this one from Ullman's book):

Code: Select all
Weight: &nbsp;</span>
            <input name="weight" type="text" class="text" value="
            <?php if (isset($_POST['weight'])) echo $_POST['weight']; ?>
            " size="3" maxlength="3"  /><br>
Here, if the value has been filled in, it will pass the "isset" test. Then you simply use "echo" to fill the same value back in.

Multiple choice form input is a little harder:

Code: Select all
            <div class="bmi_l">
                        <span class="b">                
Job (or Other Daily) Duties:</span><br>
<select name="job"class="text">

<option value="1" <?php if ((!isset($_POST['job'])) or ($_POST['job'] == "1"))
 echo  'selected="selected" '; ?>
>Desk Job </option>

<option value="1.03"<?php if ((isset($_POST['job'])) and ($_POST['job'] == "1.03"))
 echo  'selected="selected" '; ?>
>Move Around All Day (e.g. nurse, teacher, electrician)</option>

<option value="1.15"<?php if ((isset($_POST['job'])) and ($_POST['job'] == "1.15"))
 echo  'selected="selected" '; ?>
>Light (masseur, baker )</option>
Here we have a dropdown box. This will default to the first selection if there has not been an entry; if there has been a selection, it will re-enter it.

The means of presetting a select is: selected="selected". So here, to preset the value, we use a php conditional and echo: selected="selected" for the one we want to preset.

The first conditional is the default: if no value has been set (!isset) by the user, we echo "selected". We use an "or" in the conditional to add the case when the user has selected the first button; in either case, we want to preset the first value.

For all other values, we use the opposite. If a value has been set (isset), and the set value is the same as the selection's value, we preset the value to that selection. This actually works!

For radio buttons, we do the exact same thing, except we echo checked="checked". (Notice that strings and numerical values are treated exactly the same in all the examples.):

Code: Select all
Do you do regular weight training?</span><br>

            <input type="radio" name="muscle" value="1" class="text"
            <?php if ((!isset($_POST['muscle'])) or ($_POST['muscle'] == "1"))
             echo  'checked="checked" '; ?> >&nbsp;
   Occasionally or never.&nbsp;&nbsp;&nbsp;<br>

            <input type="radio" name="muscle" value="1.05"class="text"
            <?php if ((isset($_POST['muscle'])) and    ($_POST['muscle'] == "1.05"))
            echo  'checked="checked" '; ?>>&nbsp;
  Yes, as part of my exercise routine.<br />

            <input type="radio" name="muscle" value="1.2"class="text"
            <?php if ((isset($_POST['muscle'])) and    ($_POST['muscle'] == "1.2"))
            echo  'checked="checked" '; ?>>&nbsp;
  Yes and I have gained significant muscle bulk.<br />
I haven't done any checkboxes yet, and there might be an additional challenge with them, if someone wants to try. I'm about to leave for holiday. I'd start with the radio button form. If it doesn't work, my next idea would be to add a regular expression search.

If you're wondering about the strange form entries, this is from a BMI (Body Mass Index) calculator and Calories Required calculator I've been making. It's not fully styled or fully functional yet, but you can see it at
http://www.dhreport.com/articles/foodvalues/bmi.php

I don't know where it will be when I leave for the week, and I'm sure some of the function will be in midstream development, but some of it should be working. The entire "foodvalue" directory is just a day or two from completion.
Reply With Quote

  #2 (permalink)  
Old Oct 6th, 2006, 19:56
Most Reputable Member
Join Date: Apr 2006
Location: Cornwall, UK
Posts: 1,310
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via Skype™ to ukgeoff
Re: Setting Form Values to Previously Entered Values

The checkbox is a little tricker because when you check a checkbox what gets passed back is the value of 'value'.

When you want to reshow the form, you need to set the 'checked' parameter for the box to appear checked not the value parameter.

Hopefully the code snippets below will make it clear.
Code: Select all
               if ($_POST['OptIn'] == 'Yes') {
                   $optin = "checked='Yes'";
               }
               else {
                   $optin = '';
               }   

<input id="optin" type="checkbox" name="OptIn" value = 'Yes' <?php print ($optin); ?>  />
Reply With Quote
  #3 (permalink)  
Old Oct 7th, 2006, 04:05
Reputable Member
Join Date: Jul 2005
Location: Melksham, Wilts, UK
Posts: 293
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Setting Form Values to Previously Entered Values

Yes, "sticky fields" (as I know them) are a vital part of a user-friendly application.

Ideally, you should go a little further and protect the echoed text against user inputs that include characters such as " ' \ and <. Try entering 6' (for six feet) or "33 onto the form who's URL you gave and you'll find the echos are rather odd. Would people really do such a thing? Absolutely they would - it's the basis of things like 'injection attacks' against a site! People will enter all sorts of things to try to find a hole in your security, and once they spot that you don't sticky your fields quite right, they'll take it as a clue that it's worth their while to hunt for strings that produce more sinister side effects that the ones I've suggested as examples for you to look at.

With this additional logic, your code will get more complex - indeed, your select and checkbox code is already verging on the verbose. Put the common code into a function so that it's overall much shorter, so easier to maintain ... and that will also ensure that all you tests and fixes, once tested for one input element, should work consistently for all of the others of the same type.

Some of this stuff isn't intuative. I've just completed the presentation of two PHP courses this week for the same company. The first group, fairly new to PHP, followed through the excercise that "bullet proof"s a sticky input box with a degree of doubt as to how vital it was for their particular applications. The second group, who have had rather more practise at PHP already, were delighted to apply the techniques I've mentioned in this post- "so that's how to keep the code manageable and robust" they said - a lightbulb moment.

Last edited by grahame; Oct 7th, 2006 at 04:15.
Reply With Quote
  #4 (permalink)  
Old Oct 13th, 2006, 17:16
masonbarge's Avatar
Highly Reputable Member
Join Date: Jan 2006
Location: Atlanta GA
Posts: 631
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Setting Form Values to Previously Entered Values

Thanks guys. I haven't done any security work yet but I'll be sure to remember to add some basic injection attack defense to the sticky.

It hadn't occurred to me to build a function. It took about 1/10 second for me to slap my forehead and think "well, duh". Thx for the tip, I'll do it asap.

I don't have any sticky checkboxes but it will save me some time if I ever do. I did enjoy figuring out how to do the others from first principles.
Reply With Quote
  #5 (permalink)  
Old Oct 16th, 2006, 22:05
masonbarge's Avatar
Highly Reputable Member
Join Date: Jan 2006
Location: Atlanta GA
Posts: 631
Thanks: 0
Thanked 0 Times in 0 Posts
Thumbs up Re: Setting Form Values to Previously Entered Values

Okies, how about this?

Code: Select all
class StickyForms  {
    
    function defRadio ($namex, $valuex)  {
        if (($_POST[$namex] == $valuex) || (!isset($_POST[$namex]))) {
        echo 'checked="checked"';
        } else {
        return null;
        }
    }

    function altRadio ($namey, $valuey)  {
        if ($_POST[$namey] == $valuey)  {
            echo 'checked="checked"';
        } else {
        return null;
        }
    }
}  // END OF CLASS
And then in the .php file:

Code: Select all
Do you do regular weight training?</span><br>

            <input type="radio" name="muscle" value="1"
            <?php            
            $sticky = New StickyForms;
            $sticky->defRadio('muscle', 1);             
             ?> 
            >&nbsp;
Occasionally or never.<br>

            <input type="radio" name="muscle" value="1.05"
            <?php
            $sticky->altRadio('muscle', 1.05); 
            ?>
            >&nbsp;
Yes, as part of my exercise routine.<br />

            <input type="radio" name="muscle" value="1.2"
            <?php
            $sticky->altRadio('muscle', 1.2); 
            ?>
            >&nbsp;
Yes and I have gained significant muscle bulk.<br />
etc.
Before I made the class, I had the function on the php page using the ternary operator
Code: Select all
function defRadio ($namex, $valuex)  {
return ($_POST[$namex] == $valuex) || (!isset($_POST[$namex])) ? 'checked="checked" : null;
}
This was easy to use inside a php page, because I could set a variable to the function and echo the variable, e.g.
Code: Select all
$ch = defRadio (...);
echo $ch;
However, I couldn't figure out how to echo the return from a class formula and the ternary form didn't seem to like an internal echo.

Thx for the push, I needed to get comfortable with this on a real page.
Reply With Quote
  #6 (permalink)  
Old Oct 17th, 2006, 02:08
Reputable Member
Join Date: Jul 2005
Location: Melksham, Wilts, UK
Posts: 293
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Setting Form Values to Previously Entered Values

I would tend to generalise further (and perhaps not bother with objects) ... to give you an idea, here's a (working, tested) example:

Code: Select all
<?php

function mystickyradio($spec) {
        $html = "<tr><td>".htmlspecialchars($spec[0])."</td><td>";
        $bname = htmlspecialchars($spec[1]);
        for ($k=2; $k<count($spec); $k+=2) {
                $chkd = ($_REQUEST[$spec[1]] == $spec[$k+1]) ? " checked" : "";
                $html .= "<input type=\"radio\" name=\"$bname\"";
                $html .= " value=\"".htmlspecialchars($spec[$k+1])."\"$chkd>";
                $html .= htmlspecialchars($spec[$k])."<br>";
                }
        $html .= "</td></tr>";
        return $html;
        }

$rb1 = array("Do you do regular weight training?","muscle",
        "Occasionally or never","1",
        "Yes, as part of my exercise routine","1.2",
        "Yes, and I'm a bulky lad","1.5");

$rb2 = array("Select your age range","old",
        "Under 21","0-20",
        "21 to 65","midlife",
        "over 65","old");

$form = "<form method=\"POST\"><table border=1>";
$form .= mystickyradio($rb1);
$form .= mystickyradio($rb2);
$form .= "<tr><td>&nbsp;</td><td><input type=\"submit\"></td></tr>";
$form .= "</table></form>";

?>
<html>
<head>
<title>Data driven sticky radio boxes</title>
</head>
<body>
<h1>Demo Sticky form from parameters</h1>
Please fill in this form<br>
<?= $form ?>
<hr>
Instructions, copyright, etc
</body>
</html>
Put functions such as myradio into an include file, share 'em between all your applications, read definition arrays such as $rb1 and $rb2 from file ... and you've got a very quick way of doing future coding just by changing your data.
Reply With Quote
  #7 (permalink)  
Old Oct 17th, 2006, 17:36
masonbarge's Avatar
Highly Reputable Member
Join Date: Jan 2006
Location: Atlanta GA
Posts: 631
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Setting Form Values to Previously Entered Values

Actually, the main reason I did a class was for self-education, i.e. my "assignment" was to create a class with a function and use it in a live page.

Your code made my eyes boggle. Two utterly different methods with the same result.

Thanks for posting it -- I'm just starting with security issues, so the htmlspecialchars() usage was especially helpful.

Question: Could you just use a regular expression restricting the input to one of the button values?
Reply With Quote
Reply

Tags
default, form, php

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem setting the left/right/top/bottom padding of a table to different values tonyb Web Page Design 2 May 2nd, 2008 20:30
Taking values from a form without sending it... Mazinger JavaScript Forum 4 Jan 8th, 2008 18:39
form not updating values djanim8 Classic ASP 0 Dec 10th, 2005 19:05
Multiple Choice Form Values Andy K PHP Forum 9 Aug 30th, 2005 12:01
Assign string values to integer values of a session variable Andy K Classic ASP 1 Jul 13th, 2005 08:29


All times are GMT. The time now is 06:00.


Powered by vBulletin®
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC8
© 2003-2008 Webforumz.com : All Rights Reserved

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43