Solved

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

Posted on 2014-04-17
17
139 Views
Last Modified: 2014-04-19
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?
0
Comment
Question by:brucegust
  • 5
  • 4
  • 3
  • +2
17 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 40007365
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?
0
 

Author Comment

by:brucegust
ID: 40007379
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.
0
 
LVL 17

Expert Comment

by:bigeven2002
ID: 40007385
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.
0
 

Author Comment

by:brucegust
ID: 40007390
bigeven - what would that look like?
0
 
LVL 17

Assisted Solution

by:bigeven2002
bigeven2002 earned 125 total points
ID: 40007425
I think like this:
if($_POST['entityCB'.$i])

Now that I think about it, it maybe have the concatenation that was incorrect so try this too:
if(isset($_POST['entityCB'.$i]))
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 40007436
That doesn't make any sense.  Is this related to your previous question?
0
 

Author Comment

by:brucegust
ID: 40007457
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?
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 125 total points
ID: 40007514
This is a very common question because the way HTML forms handle checkboxes is rather confusing and counter-intuitive.  See if this article helps lift the veil.  There are some examples included.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_5450-Common-Sense-Examples-Using-Checkboxes-with-HTML-JavaScript-and-PHP.html
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:brucegust
ID: 40007555
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?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40007596
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

0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 125 total points
ID: 40007644
I just did (and re-did)  a multi-page form where I needed to re-display previous selections if they decided to go back to a previous page.  Checkboxes are part of it.

#1. When each page is submitted, I set a default value for the items from the form.
#2. I check the $_POST data to see if anything was submitted.  If it was I update the data.
#3. I also update a $_SESSION variable with that data.

If someone goes back to a previous page, I set the default value then check the $_SESSION data to see if something else had already been selected.  Then I update the form with the correct data.  It is a long and tedious procedure, a lot like secretarial typing, but then a lot of programming is just that.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40007659
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

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 125 total points
ID: 40007676
To amend your code it would look something like this
<table width='$leftcol' cellspacing='0' cellpadding='0'>
  <tr>
    <td colspan='2' class='colnav' align='center'>available roles (".$modelrolelist["count"].")</td>
  </tr>";
$rc_count = 1;
// RETRIEVE THE CHECKEBOXES ARRAY
$checkboxes = $_POST['entityCB'];
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>";
// SET THE CHECKED STATUS
$checked = empty($checkboxes[$i]) ? '' : ' checked="checked"';    
// USE ONLY ONE OUTPUT LINE
echo '<input type="Checkbox" name="entityCB['.$i.']" ' . $checked . ' 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

0
 
LVL 17

Expert Comment

by:bigeven2002
ID: 40007688
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 :)
0
 

Author Comment

by:brucegust
ID: 40007806
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!
0
 
LVL 17

Expert Comment

by:bigeven2002
ID: 40007848
Awesome, glad that worked out!
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40010177
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

0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now