Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

This should be easy, but it ain't working...

All I want to do is check to see if a particular checkbox was checked when the form was submitted.

The thing that makes it a little challenging is that it's part of an array and every time I try to identify it in the context of its corresponding $i value, I'm coming up short.

Here's what I've got:

echo "
				<tr>
<td width='25' align='center' $rclass>";
if(isset($_POST['entityCB".$i."']))
{
echo "<input type='Checkbox' name='entityCB".$i."' checked value='1'>";
}
else
{
echo"<input type='Checkbox' name='entityCB".$i."' value='1'>";
}
echo"<input type='Hidden' name='entityID".$i."' value='".$modelrolelist[$i]["workqueueroleid"]."'>
</td>

Open in new window


Can you smell what I'm cooking?

All I want to do is write that if(isset($_POST['entityCB".$i."'])) in a way where the $i is recognized for what it is and right now, I'm coming up short.

Thoughts?
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Un-checked checkboxes are not submitted.  At all.  Where are you defining $i?  It's not in the code that you have posted.

What does the form code look like?
Avatar of Bruce Gust

ASKER

Hey, Dave!

I'm trying to create a situation where a user can submit a form that, even if doesn't pass validation, still has the fields the user completed left in tact. So that's where all this is going.

Here's the form:

<table width='$leftcol' cellspacing='0' cellpadding='0'>
<tr>
<td colspan='2' class='colnav' align='center'>available roles (".$modelrolelist["count"].")</td>
</tr>";
$rc_count = 1;
for ($i=1;$i<=$modelrolelist["count"];$i++) {
$rc_count++;
$hlf = floor($rc_count/2);
$dbl = $hlf*2;
				
if ($rc_count != $dbl)
$rclass = " class=''";
else
$rclass = " class='rcolor'";
echo "
<tr>
<td width='25' align='center' $rclass>";
if(isset($_POST['entityCB'))
{
echo "<input type='Checkbox' name='entityCB".$i."' checked value='1'>";
}
else
{
echo"<input type='Checkbox' name='entityCB".$i."' value='1'>";
}
echo"<input type='Hidden' name='entityID".$i."' value='".$modelrolelist[$i]["workqueueroleid"]."'>
					</td>
<td width='".($leftcol-25)."' $rclass><span class='text'>";
if(trim($modelrolelist[$i]["overridename"])!="")
{
if($modelrolelist[$i]["corpflag"]>0)
{
echo $modelrolelist[$i]["defaultname"].' ('.$modelrolelist[$i]["overridename"].')'.' | corporate';
}
else
{
echo $modelrolelist[$i]["defaultname"].' ('.$modelrolelist[$i]["overridename"].')';
}
}
else
{

Open in new window


This isn't everything, but at least you can see where my "for" loop starts and where $i is coming from.
Hello,
Try taking the isset function out of the conditional statement.  This way php will check if the var is true, not empty, or 1.
bigeven - what would that look like?
SOLUTION
Avatar of bigeven2002
bigeven2002
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That doesn't make any sense.  Is this related to your previous question?
Here's something that's working:

$bubba = "&#36;_POST['entityCB";
$bubba .=$i;
$bubba .="']";
if(isset($bubba))
{
echo "<input type='Checkbox' name='entityCB".$i."' checked value='1'>";
}
else
{
echo"<input type='Checkbox' name='entityCB".$i."' value='1'>";
}
}

Basically, set up a variable and put my "$_POST" stuff in there and at least PHP can read it. The only problem now is that it's telling me that every checkbox is set so I'm getting a checkmark in every box.

Now what?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ray, sweet article. Well written and I ran through your examples. My dilemma remains, however, in that when my user submits the form, if it doesn't pass validation, I want to preserve whatever options they've chosen, hence the:

if(isset($_POST['entityCB1'])
{
<input type="checkbox" name="entityCB1" value=1 checked>
}

Right now, everyone of my boxes is checked and I don't know why. Any ideas?
I don't have an example that shows how to remember checkboxes beyond what is written in the article -- where it remembers the checked checkboxes from request to request.  You can try that script here:
http://iconoun.com/demo/EE_checkbox_demo.php

Maybe something like this will be helpful?
http://iconoun.com/demo/form_highlight_errors.php

<?php // demo/form_highlight_errors.php
error_reporting(E_ALL);

/**
 * DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT, AND REMEMBER VALID INPUTS
 * CLIENT IS ASKED TO PUT IN A VALUE
 * IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
 * WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
 * WE TURN THE FORM BORDER RED
 * SEE http://www.w3schools.com/CSS/pr_class_visibility.asp
 */


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Why not make your checkboxes arrays like this

<input type="checkbox" name="entityCB[1]" />
<input type="checkbox" name="entityCB[2]" />
...

Open in new window

That way you can check the array variable like this

$checkboxes = $_POST['entityCB'];
...
for($i ...)
{
// Set the checked status so you can loose the if / then on the output
$checked = empty($checkboxes[$i]) ? '' : ' checked="checked" ';

// if the checkbox is not checked then the $checked will be blank otherwise it
// will be set to checked - next line then will check / uncheck as required
echo '<input type="checkebox" name="entityCB[' . $i . ']" ' . $checked '/>';
...
}

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think I misunderstood the question.  I'll need to look at this again when I get home this evening if the question is still open.  Too much to look at on a mobile phone :)
Guys...I got it!

I'd like to say that I figured it out, but it was my boss who just knocked it out of the park within 5 minutes after I'd been sitting here feeling like my brain was submerged in a vat of banana pudding. I don't know, does anyone else ever feel like this? It's like playing chess, sometimes.

In any event, here's what was done:

if(isset($_POST['SubmitButton']))
                              {
                              /*$bubba = "&#36;_POST['entityCB";
                              $bubba .=$i;
                              $bubba .="']";
                    */
 eval('$bubba = $_POST["entityCB'.$i.'"];');
if(isset($bubba))
{
echo "<input type='Checkbox' name='entityCB".$i."' checked value='1'>";
}
else
{
echo"<input type='Checkbox' name='entityCB".$i."' value='1'>";
}
}
else
{
echo"<input type='Checkbox' name='entityCB".$i."' value='1'>";
}

By packaging my "posted" information in the context of an email, you're able to maintain your character credibility. By that I mean, me doing my "$bubba=..." was resulting in nothing other than a string and pure pointlessness on the other end.

With the eval, I get my value that I can then check and it's all good from there.

As always, thanks for weighing in and I'm always awed by the knowledge represented by the experts-exchange brain trust.

Go, fight, win!
Awesome, glad that worked out!
I was away so apologies for this late post.

There is (in my experience) almost no valid reason to use eval in code. If your solution uses eval then you should go back and re-eval the solution because there is something wrong.

Code posted here should do the trick. Without having access to your full code base it is difficult to provide an exact working example but here is some sample code based on your code that does demonstrate the concept.

The code makes a few changes from the original and also includes some aspects that need addressing - for instance the use of deprecated attributes such as width, align, cellpadding and cellspacing all of which should be moved to the style sheet.

Also implemented a more efficient odd / even row selection with $k = 1 - $k and checking for $k > 0;
Key elements of this sample are that
a) It uses arrays to store values -> entityCB[1], entityCB[2] etc. This makes for far easier processing on the server side.
b) It uses HEREDOC output instead of multiple quoted echos allowing for the more standard use of double quotes for attributes.

<!doctype html>
<html>
<head>
<title>Checkbox Sample</title>
</head>
<body>
<form method="post">
<?php
$modelrolelist = array('count' => 10);
echo <<< OPENTABLE
<table cellspacing='0' cellpadding='0'>
  <tr>
    <td colspan="2" class="colnav" align='center'>available roles ("{$modelrolelist["count"]}")</td>
  </tr>
OPENTABLE;

$checkboxes = isset($_POST['entityCB']) ? $_POST['entityCB'] : array();

$k=0;
for ($i=1;$i<=$modelrolelist["count"];$i++) :
  $k = 1 - $k;
  $rclass = ($k > 0) ? ' class="rcolor"' : '';
  $checked = empty($checkboxes[$i]) ? '' : ' checked="checked"';    

echo <<< ROW
  <tr>
    <td width="25" align="center"{$rclass}>
      <input type="checkbox" name="entityCB[{$i}]" {$checked} value="1">
      <input type="hidden" name="entityID[{$i}" value="1">
    </td>
    <td {$rclass}><span class="text">CHECKBOX LABLE {$i}</span></td>
  </tr>
ROW;
 
 endfor;
 echo <<< CLOSETABLE
 </table>
CLOSETABLE;
?>
<input type="submit" value="Submit" />
<form>
 </body>
 </html>

Open in new window