Forum Moderators: coopster
I'm trying to automate form validation - so far I've had good success with text fields and select lists, but now I'm on to checkboxes and I'm having a problem.
I set up my form page with the following at the top:
$_SESSION['CheckBoxes'] = array
(
'food'
);
"food" is an array name that I use on all checkboxes on the page like so:
<input
type="checkbox"
name="food[apples]"
value="apples"
id="rel"
title="Title"
class="checkBox"
<?php if(isset($food['apples'])) echo ' checked';?>
/>
<input
type="checkbox"
name="food[oranges]"
value="oranges"
id="rel"
title="Title"
class="checkBox"
<?php if(isset($food['oranges'])) echo ' checked';?>
/>
and so on.
When the page is submitted, a generic validation form is included that handles all form elements.
If $_SESSION['CheckBoxes'] on the preceding page is not NULL (it contains an array or array names) then the script checks to see if any check boxes have been ticked:
if($_SESSION['CheckBoxes']!= NULL)
{
//if array keys exists in the $_SESSION var, then step through the values associated with each key name present
for($i = 0; $i < count($_SESSION['CheckBoxes']); $i++)
{
//prepend the first key name with a '$' so the contents of $check appears as an array name
$check = '$' . $_SESSION['CheckBoxes'][$i];
//Determine if the array name has been submitted (one of the boxes have been checked)
if(isset($check))
{//if the array name is set, echo the contents
foreach($check as $key => $value)
{
echo $value . "<br>";
}
}
Of course, it's not working. If I manually do: if(isset($food)) print_r($food) the result is as expected: all checkboxes that have been activated show up. But all my little script above echos is "$food" and I don't understand why. I've thought that maybe the type array isn't being recognized because I'm pulling it from a $_Session, so I've tried casting it back as type array but that isn't working either.
Anyone have any ideas that would help move me forward?
Neophyte