2

If I have a form with two checkboxes that have have the same array as name attribute

name="1_1[]"

and neither of those checkboxes is ticked, is there any way I can know they were present in the form? These fields are not being sent through the $_POST array if they are unchecked.

I'm asking this cause these name values are being generated dynamically, I don't always know what they are and I have to validate them (make sure at least one of the two is checked).

Do I have to start using hidden fields to send the name attribute values through, or is there a better way?

stef
  • 26,771
  • 31
  • 105
  • 143
  • Put this in above the checkboxes: EDIT: Forgot to read the last line. I actually use the hidden fields myself and I think it is the easiest way. Else you should validate it at the server side page whether the field is set or not. – Dennis Lauritzen Mar 19 '11 at 22:34

2 Answers2

2

Using a hidden field would probably be the most sensible way if you really can't get to the data on the receiving page, if you want to keep on using checkboxes. You can't get a checkbox to send a value if it's unchecked, that's how they work.

On the other hand, the receiving page not knowing about what data to expect sounds really odd. Can't you just re-fetch the same data?

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • The receiving page doesn't know what data to expect cause the form is built dynamically (ala surveymonkey) and the name param contains concatenated DB id's. Thanks, I'll go with hidden fields. – stef Mar 20 '11 at 11:05
  • @stef: Where do you get the data that defines what fields to display in the first place? – Matti Virkkunen Mar 20 '11 at 11:56
  • This is part of a survey designer application, so the fields' parameters are stored in a DB. – stef Mar 21 '11 at 09:04
  • @stef: Can't you just get the parameters off the DB again and then compare them with the POST data? – Matti Virkkunen Mar 21 '11 at 09:30
1

The fact that they're not in the $_POST array means you can use isset() to see if they've been set.

If you've got two checkboxes and one needs to be set at least, you could do:

$missingValue = TRUE;

if(isset($_POST['checkbox_foo'] || isset($_POST['checkbox_bar'])
{
    $missingValue = FALSE;
}

If that's not good enough, you'll have to go with hidden fields.

markus
  • 40,136
  • 23
  • 97
  • 142