...

View Full Version : Rechecking checkboxes after a form submit



littlejones
10-26-2006, 06:37 PM
Hi there,

My problem is, if a user fills in a form which includes checkboxes and they have left a required field blank, I need to reload the form and keep the checkboxes they selected checked so that they don't have to redo it.

So far I've come up with this solution but am wondering whether or not there is a simpler or more productive one...I've left out parts of the form which are irrelevant.



<?php $category = $_POST['category']; ?>


<div class="divCheck">
<div><input type="checkbox" name="category[]"
<?php if(in_array(1 ,$category)) echo "checked";?> value="1"style="width: 12px;"/>&nbsp;General</div><br/>
<div><input type="checkbox" name="category[]"
<?php if(in_array(2 ,$category)) echo "checked";?> value="2" style="width: 12px;"/>&nbsp;Immigration</div><br/>
<div><input type="checkbox" name="category[]"
<?php if(in_array(3 ,$category)) echo "checked";?> value="3" style="width: 12px;"/>&nbsp;Employment</div><br/>
<div><input type="checkbox" name="category[]"
<?php if(in_array(4 ,$category)) echo "checked";?> value="4" style="width: 12px;"/>&nbsp;Housing</div><br /><br />
</div

Thanks a bunch in advance!

littlejones
10-27-2006, 10:23 AM
I guess the way I've done must be the best way then? :thumbsup:

CanMike
10-27-2006, 09:11 PM
Funny you should ask. I just went through the same thing, but I had to retain all of the data submitted, from radio, checkbox and text.

Here's the solution that I used (after a great deal of help from this forum) and it works beautifully.



<?php # display.php

$ptype = '';
$parea = '';
$pcity = '';


//Check if the form has been submitted
if (isset($_POST['submit']))
{
$type = $_POST['fr_type'];
$area = $_POST['fr_area'];
$city = $_POST['fr_city'];

$ptype = $type;
$parea = $area;
$pcity = $city;

}
?>

<html>
<head>
<title>Display Test</title>
</head>
<body>
<form name="display_form" method="POST" action="display.php">
<p align="center">&nbsp;</p>
<table border="0">
<tr>
<td width="145"></td>
<td width="254"><b>Area</b></td>
<td width="217">
<select size="1" name="fr_area">
<option <?php echo ($parea == 'Urban') ? 'selected' : ''; ?>>Urban</option>
<option <?php echo ($parea == 'Rural') ? 'selected' : ''; ?>>Rural</option>
</select>
</td>
<td width="202"></td>
</tr>
<tr>
<td width="145"></td>
<td width="254"<b>Location</b></td>
<td width="217">
<input type="text" name="fr_city" size="20" maxlength="35" value="<?php echo $pcity; ?>">
</td>
<td width="202"></td>
</tr>


<tr>
<td width="145">&nbsp;</td>
<td width="254"><b>Type of Accomodations</b></td>
<td width="217">
<p align="left">
Male <input type="radio" name="fr_type" value="male" <?php echo ($ptype == 'male') ? 'checked' : ''; ?>>
Female <input type="radio" name="fr_type" value="female" <?php echo ($ptype == 'female') ? 'checked' : ''; ?>>
<td width="202">&nbsp;</td>
</tr>
<tr>
<td width="145">&nbsp;</td>
<td width="254"><input type="submit" name="submit" value="List" /></td>
</tr>
</table>
</form>
</body>
</html>

This is just a small example.

Hope it helps

littlejones
10-30-2006, 11:54 AM
Thanks for responding.

I can see how that works with radio boxes as the user can only select one box, but with checkboxes the user is able to select as many as they want and having tried your code in my implementation only one checkbox is re-checked after the form is submitted :mad:

Although what I've done works when I check checkboxes and submit the form

<?php if(in_array(1,$category)) echo "checked";?>

If none of the boxes are checked and the form is submitted i get the following error:

Warning: in_array(): Wrong datatype for second argument in /data/webs/site/www/contact.php on line 119
value="1"style="width: 12px;"/> General

That's all the information it gives, and it does this for each checkbox on the page. The error seems pretty straightforward but in fact I'm yet to figure out a solution.

Here is a snippet of my code:

$category = $_POST['category'];

<div><input type="checkbox" name="category[]" <?php if(in_array(1,$category)) echo "checked";?> value="1"style="width: 12px;"/>&nbsp;General</div><br/>
<div><input type="checkbox" name="category[]" <?php if(in_array(2,$category)) echo "checked";?> value="2" style="width: 12px;"/>&nbsp;Immigration</div><br/>
<div><input type="checkbox" name="category[]"<?php if(in_array(3,$category)) echo "checked";?> value="3" style="width: 12px;"/>&nbsp;Employment</div><br/>
<div><input type="checkbox" name="category[]" <?php if(in_array(4,$category)) echo "checked";?> value="4" style="width: 12px;"/>&nbsp;Housing</div><br /><br />

Any help is greatly appreciated!!! :D

CanMike
10-31-2006, 06:18 PM
Well, I cheated. I set display_errors in the PHP.ini files to "Off" (I have administrator rights on my unix server), then catch the error in a 'IF statement'.


<?php # display.php

$ptype = '';
$parea = '';
$pcity = '';

$colours = array();
$colour_selected = FALSE;

ini_set ('display_errors', 1); <-- Temp override of php.ini argument

//Initialize array values;
for($idx=1; $idx<4; $idx++)
{
$colours[$idx] = 'off';
}

//Check if the form has been submitted
if (isset($_POST['submit']))
{
$type = $_POST['fr_type'];
$area = $_POST['fr_area'];
$city = $_POST['fr_city'];

if (is_array($_POST['fr_colours']))
{
$colour_selected = TRUE;
}
else
{
print "Please enter at least one colour"; <-- Catch error here
}



if ($colour_selected)
{
foreach ($_POST['fr_colours'] as $fr_c) {
$colours[$fr_c] = 'on';
}
}


$ptype = $type;
$parea = $area;
$pcity = $city;
}
?>

<html>
<head>
<title>Display Test</title>
</head>
<body>
<form name="display_form" method="POST" action="display.php">
<p align="center">&nbsp;</p>
<table bgcolor="honeydew">
<tr>
<td width="145"></td>
<td width="254"><b>Favourite Colour</b></td>
<td width="217">
<p align="left">
<input type="checkbox" name="fr_colours[]" value="1" <?php echo($colours[1] == 'on') ? 'checked' : ''; ?>>Green
<input type="checkbox" name="fr_colours[]" value="2" <?php echo($colours[2] == 'on') ? 'checked' : ''; ?>>Blue
<input type="checkbox" name="fr_colours[]" value="3" <?php echo($colours[3] == 'on') ? 'checked' : ''; ?>>Yellow
</p>
</td>
<td width="202"></td>
</tr>
<tr>
<td width="145"></td>
<td width="254"><b>Area</b></td>
<td width="217">
<select size="1" name="fr_area">
<option <?php echo ($parea == 'Urban') ? 'selected' : ''; ?>>Urban</option>
<option <?php echo ($parea == 'Rural') ? 'selected' : ''; ?>>Rural</option>
</select>
</td>
<td width="202"></td>
</tr>
<tr>
<td width="145"></td>
<td width="254"<b>Location</b></td>
<td width="217">
<input type="text" name="fr_city" size="20" maxlength="35" value="<?php echo $pcity; ?>">
</td>
<td width="202"></td>
</tr>


<tr>
<td width="145">&nbsp;</td>
<td width="254"><b>Type of Accomodations</b></td>
<td width="217">
<p align="left">
Male <input type="radio" name="fr_type" value="male" checked <?php echo ($ptype == 'male') ? 'checked' : ''; ?>>
Female <input type="radio" name="fr_type" value="female" <?php echo ($ptype == 'female') ? 'checked' : ''; ?>></p>
<td width="202">&nbsp;</td>
</tr>
<tr>
<td width="145">&nbsp;</td>
<td width="254"><input type="submit" name="submit" value="List" /></td>
</tr>
</table>
</form>
</body>
</html>

Then, to show any error I set ini_set('display_errors', 1) to temporarily override the php.ini file.

To the best of my knowledge, users must select at least one checkbox, otherwise, PHP throws an error.

Notice also that I initialize an array and load the values from the form. I find it a lot easier to debug later.

]I know that somewhere, there a better solution to this problem and now it's buggin' me.

littlejones
10-31-2006, 08:18 PM
I've got a solution to my problem!

Basically the checkboxes are in an array, and if any of them aren't ticked then php throws an error like you say. So what I did was something along the lines of...


if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($checkboxes == null) $checkboxes = array ("",""); //this stops it giving the wrong datatype error because you are actually giving it values (albeit empty ones)

}

Obviously more code goes in there but you get the idea. By giving the checkbox array some values when it is left empty then it doesn't have a chance to throw errors. :confused:

CanMike
10-31-2006, 09:10 PM
How do you get around the error thrown by PHP when you issue:

$catergory = $_POST('category');

I'm not experience enough to know how to check if 'type=checkbox' is null.
The only way I know to check returns from a form is to issue a $_POST, which will thrown an error if the array is empty.

It sort of a chicken and egg thing. If I need to know if the checkbox array is empty the only way to check is to issue a $_POST['<checkbox name>'], which throws an error.

Could you supply a more complete example.

littlejones
10-31-2006, 10:24 PM
Ok, I'm new to php and programming myself, but have sort of been doing a crash course as a junior developer for a web agency in London so have had no choice but to try and learn as fast as I can so I can actually be of some use to the company. So anyway, this is along the lines of what I did...but actually the code I used is on my work computer so I'm going from memory. If you still don't understand at the end of this just say so and I'll post all my code tomorrow when I'm at work.



<?php

$checkboxes = $_POST['checkboxes']; //in other words $category now stores an array of whatever checkboxes were selected in the form, BUT only if the submit button was pressed (form posted), otherwise this code is ignored.
if($checkboxes == null) $checkboxes = array("",""); //This is absolutely crucial to avoid a 'wrong data-type error, but it's probably not necessary to make $checkboxes an array, you could probably say $checkboxes = "whatever_you_want";


// ONLY IF the form was submitted do the following
if($SERVER['REQUEST_METHOD'] == 'POST')
{


?>
<html>
<head><title>RECHECKING CHECKBOXES TEST PAGE</title></head>
<body>
<form action="<?php echo $PHP_SELF; //This would be the same as putting the page name in but is better because if you change page name in the future you won't have to change this?>" method="post">

<input type="checkbox" name="checkboxes[]" <?php if(in_array(1,$checkboxes)) echo "checked"; //IF 1 is found in the array it means the first checkbox was checked, so recheck it!!?> value="1">Checkbox 1</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(2,$checkboxes)) echo "checked"; ?> value="2">Checkbox 2</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(3,$checkboxes)) echo "checked"; ?> value="3">Checkbox 3</input><br/><br/>
<input type="submit" value="Lets Roll!"/>

</form>
</body>
</html>
<?php
}
//OTHERWISE do this... (So this is what will show when the page is first loaded and the submit button has not been pressed. It's identical to above, and so there is probably a better way to go about this rather than duplicating it.
else
{

?>
<html>
<head><title>RECHECKING CHECKBOXES TEST PAGE</title></head>
<body>
<form action="<?php echo $PHP_SELF; //This would be the same as putting the page name in but is better because if you change page name in the future you won't have to change this?>" method="post">

<input type="checkbox" name="checkboxes[]" <?php if(in_array(1,$checkboxes)) echo "checked"; //IF 1 is found in the array it means the first checkbox was checked, so recheck it!!?> value="1">Checkbox 1</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(2,$checkboxes)) echo "checked"; ?> value="2">Checkbox 2</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(3,$checkboxes)) echo "checked"; ?> value="3">Checkbox 3</input><br/><br/>
<input type="submit" value="Lets Roll!"/>
</form>
</body>
</html>
<?php
}
?>




I just chucked this into a page for you so you can test it and see that it works. I hope it works for you, please let me know!

http://www.littlejones.co.uk/checkbox.php

littlejones
10-31-2006, 10:31 PM
I don't know if this helps but it confused me for a long time. There are so many ways to do the same thing in php. To check if a variable is empty you could do it many ways...




if($checkboxes == null) do some code...

if($checkboxes == "") do some code...

if(empty($checkboxes)) do some code...



And I've no doubt there are many more ways to achieve the same result. Crazy huh :confused:

CanMike
11-01-2006, 04:55 PM
Still throwing errors:

"Undefined index: checkboxes" on initial load on the line $checkboxes = $_POST['checkboxes'];

I pasted your source code into an editor, changed a typo ($SERVER to $_SERVER) and (action="<?php echo $PHP_SELF?>" to action="<? echo $_SERVER['PHP_SELF']?>").

I also reset the php.ini argument 'display_errors' to "On" on the unix server.

There is one statement you made that I'm having a hard time understanding:

// ONLY IF the form was submitted do the following

But, the line <input type="submit" value="Lets Roll!"/> is a submit.

My limited understanding of PHP and Webforms is that you must submit a form from the website to the server via the submit argument!?:confused:

So, my question is: How to you NOT submit a form.

Your away ahead of me on this stuff, I'm still trying to learn PHP. By profession I'm an Oracle DBA with skills writing SQL and PL/SQL and by necessity Java and C++.

I'm working from home and I've got a couple of clients I'm trying to convince to convert to PHP/MySQL, since it's free and their running small businesses. So I've only have to hold values from text boxes and radio buttons.

I'd like to see your code that hold the checkbox values without throwing an error.

littlejones
11-01-2006, 09:38 PM
Did you follow the link to www.littlejones.co.uk/checkbox.php

Does that work for you? This is the exact code used to make that...



<?php

$checkboxes = $_POST['checkboxes']; //in other words $category now stores an array of whatever checkboxes were selected in the form, BUT only if the submit button was pressed (form posted), otherwise this code is ignored.
if($checkboxes == null) $checkboxes = array("",""); //This is absolutely crucial to avoid a 'wrong data-type error, but it's probably not necessary to make $checkboxes an array, you could probably say $checkboxes = "whatever_you_want";


// ONLY IF the form was submitted do the following
if($_SERVER['REQUEST_METHOD'] == 'POST')
{


?>
<html>
<head><title>RECHECKING CHECKBOXES TEST PAGE</title></head>
<body>
<form action="<?php echo $PHP_SELF; //This would be the same as putting the page name in but is better because if you change page name in the future you won't have to change this?>" method="post">

<input type="checkbox" name="checkboxes[]" <?php if(in_array(1,$checkboxes)) echo "checked"; //IF 1 is found in the array it means the first checkbox was checked, so recheck it!!?> value="1">Checkbox 1</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(2,$checkboxes)) echo "checked"; ?> value="2">Checkbox 2</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(3,$checkboxes)) echo "checked"; ?> value="3">Checkbox 3</input><br/><br/>
<input type="submit" value="Lets Roll!"/>

</form>
</body>
</html>
<?php
}
//OTHERWISE do this... (So this is what will show when the page is first loaded and the submit button has not been pressed. It's identical to above, and so there is probably a better way to go about this rather than duplicating it.
else
{

?>
<html>
<head><title>RECHECKING CHECKBOXES TEST PAGE</title></head>
<body>
<form action="<?php echo $PHP_SELF; //This would be the same as putting the page name in but is better because if you change page name in the future you won't have to change this?>" method="post">

<input type="checkbox" name="checkboxes[]" <?php if(in_array(1,$checkboxes)) echo "checked"; //IF 1 is found in the array it means the first checkbox was checked, so recheck it!!?> value="1">Checkbox 1</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(2,$checkboxes)) echo "checked"; ?> value="2">Checkbox 2</input>
<input type="checkbox" name="checkboxes[]" <?php if(in_array(3,$checkboxes)) echo "checked"; ?> value="3">Checkbox 3</input><br/><br/>
<input type="submit" value="Lets Roll!"/>
</form>
</body>
</html>
<?php
}
?>



I am using PHP Version 5.1.6

You can check your version by making a php file with just this code in it and then open it on your server.



<?php

echo phpinfo();

?>


It actually worked for me with $SERVER and $_SERVER and $PHP_SELF is fine, but you can also use $_SERVER['PHP_SELF']. I'm not sure about older versions though.

You could try putting the $checkboxes = $_POST['checkboxes'] code inside the IF($_SERVER['REQUEST_METHOD'] == 'POST')
{
$checkboxes = $_POST['checkboxes']
//and the rest of the code
}

Let me know how it goes and check what version you are using.

CanMike
11-01-2006, 10:05 PM
Hi,

Nope, I think I'm using PHP 4.3.9.

But, I think I found a solution, this code works:


<?php # display.php
$area = '';
$type = '';
$city = '';

//Check if the form has been submitted and validate data.
if (isset($_POST['submit']))
{

$type = $_POST['fr_type'];
$area = $_POST['fr_area'];
$city = $_POST['fr_city'];

if (isset($_REQUEST['fr_green']))
{
$green = $_REQUEST['fr_green'];
}

if (isset($_REQUEST['fr_blue']))
{
$blue = $_REQUEST['fr_blue'];
}

if (isset($_REQUEST['fr_yellow']))
{
$yellow = $_REQUEST['fr_yellow'];
}

}
?>

<html>
<head>
<title>Display Test</title>
</head>
<body>
<form name="display_form" action="display.php" method="POST">
<p align="center">&nbsp;</p>
<table bgcolor="honeydew">
<tr>
<td width="145"></td>
<td width="254"><b>Favourite Colour</b></td>
<td width="217">
<p align="left">
<input type="checkbox" name="fr_green" value="1"
<?php
if ( (isset($_REQUEST['submit'])) && (!isset($_REQUEST['fr_green'])))
{
print '';
}
elseif ( (isset($_REQUEST['submit'])) && (isset($_REQUEST['fr_green'])) )
{
print 'checked="checked"';
}
?>/>Green<br />
<input type="checkbox" name="fr_blue" value="1"
<?php
if ( (isset($_REQUEST['submit'])) && (!isset($_REQUEST['fr_blue'])))
{
print '';
}
elseif ( (isset($_REQUEST['submit'])) && (isset($_REQUEST['fr_blue'])) )
{
print 'checked="checked"';
}
?>/>Blue<br />
<input type="checkbox" name="fr_yellow" value="1"
<?php
if ( (isset($_REQUEST['submit'])) && (!isset($_REQUEST['fr_yellow'])))
{
print '';
}
elseif ( (isset($_REQUEST['submit'])) && (isset($_REQUEST['fr_yellow'])) )
{
print 'checked="checked"';
}
?>/>Yellow<br />
</p>
</td>
<td width="202"></td>
</tr>
<tr>
<td width="145"></td>
<td width="254"><b>Area</b></td>
<td width="217">
<select size="1" name="fr_area">
<option <?php echo ($area == 'Urban') ? 'selected' : ''; ?>>Urban</option>
<option <?php echo ($area == 'Rural') ? 'selected' : ''; ?>>Rural</option>
</select>
</td>
<td width="202"></td>
</tr>
<tr>
<td width="145"></td>
<td width="254"<b>Location</b></td>
<td width="217">
<input type="text" name="fr_city" size="20" maxlength="35" value="<?php echo $city; ?>">
</td>
<td width="202"></td>
</tr>


<tr>
<td width="145">&nbsp;</td>
<td width="254"><b>Type of Accomodations</b></td>
<td width="217">
<p align="left">
Male <input type="radio" name="fr_type" value="male" checked <?php echo ($type == 'male') ? 'checked' : ''; ?>>
Female <input type="radio" name="fr_type" value="female" <?php echo ($type == 'female') ? 'checked' : ''; ?>></p>
<td width="202">&nbsp;</td>
</tr> <tr>
<td width="145">&nbsp;</td>
<td width="254"><input type="submit" name="submit" value="List" /></td>
</tr>
</table>
</form>
</body>
</html>

Of course, once you figure it out it appears so straight forward. The secret is to view each checkbox argument as an distinct variable. Then check to see if it's set (isset), then act upon it. I'm I stupid.:(

If the checkbox is not selected, it's simply ignored (!isset($_REQUEST['fr_green'])), etc

Notice how in the data validation area you use the same isset check in an IF statement.

This is pretty coarse and I'm sure it can be cleaned up, but hey it works.

I'd really be interested if this works in PHP 5.1.6., and I can't believe it wouldn't.

Obviously PHP 5 has a lot of advantages than older versions. The irony is, I'm my own unix/PHP/Apache/MySQL administrator. I'm the guy that can upgrade everything.

I also followed your link to www.littlejones.co.uk/checkbox.php and it works fine.

This has been great, I learned more in the last couple of days than in the last while. Now I'll be able to use this code in my demo for the clients.

Now I better get back to my wife and finish all the stuff I've 'neglected' because I've been trying to figure out this problem.

Mike in Toronto, Canada

littlejones
11-01-2006, 10:32 PM
Just so you know, your code does indeed work in php 5.1.6

www.littlejones.co.uk/php5.php

Do you use firefox or IE? The next thing I would aim for is to learn the basics of css, as you'll notice that the link above appears differently in IE and firefox. For example I would change all of your <td width="100"> to <td style="width:100;">. It's not important at this stage but if you're doing both development design then it's worth a note.

Well done on getting it to work though, it took me a couple of days to figure out how to do it my way, and I'm a little disappointed it doesn't work in PHP 4 as I believe the site I have built will be hosted by the client on a PHP 4 server. Oh no! :eek:

CanMike
11-02-2006, 12:33 AM
Ya, the IE and Firefox well drive you nuts. I test against IE 6 and firefox and netscape 8, but for my day to day stuff, firefox. Now we have IE 7.0 either released or just about to be and I hear that IE 7 is suppost to be more 'open'. Ya, sure.

I've used CSS on a website I help 'maintain' for our family. Somehow, once they all knew I was a 'computer guy', the idea that I would be perfect to maintain a website (I didn't even know existed), seemed great. It was written using FrontPage and CSS. I had to learn the hard way. It's pretty easy to learn, but like anything else, there are a million different ways to do the same thing AND IE/firefox/netscape can display the website differently. Good luck with that.

I'd be a little concerned about your code running on PHP 4 servers. I use 3 commercial webservers for my clients and they all run PHP 4 versions. That's the main reason I haven't upgraded to PHP 5. If you have access to 4, I'll run my code on it.

Glad to see my code worked on PHP 5, but I would have been suprised if it didn't.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum