gingerandjohn.com

Removing all doubt.

gingerandjohn.com random header image

Interpreting PHP checkboxes

June 17th, 2004 by John

I've been doing some form development for the CRMA sites, and using PEAR's HTML_QuickForm for it. One of the things I have to do is interpret which checkboxes the user selects. Giving each checkbox its own name is pretty nasty, since this particular form has about 40. That also prevents me from programmatically associating related checkbox elements together.

Here's a short example: The user has to select which CRMA solution types their company provides in their products and solutions. The choices are:
* Sales
* Marketing
* Service/Help Desk

I started out writing this as:
$form->addElement('advcheckbox', 'solutionType[]', 'Type of solution (check all that apply):', 'Sales', null); $form->addElement('advcheckbox', 'solutionType[]', null, 'Marketing', null); $form->addElement('advcheckbox', 'solutionType[]', null, 'Service/Help Desk', 'null');

Checking the first option gives me the following $_POST variables:
[__solutionType] => Array ( [0] => 1 ) [solutionType] => Array ( [0] => [1] => [2] => )

I could work with this, but what I'd like to know isn't that the first element of the array is checked, but that 'Sales' is checked. Then I experimented with adding the checked value attribute to addElement as the last parameter:
$form->addElement('advcheckbox', 'solutionType[]', 'Type of solution (check all that apply):', 'Sales', null, 'Sales);

The other lines were treated similarly, but the output didn't change at all. After tracking down the only relevant entry Google could find on "quickform checkbox variable", I was able to deduce that I needed to define each element of solutionType[] specifically (again, only showing the first element as an example):
$form->addElement('advcheckbox', 'solutionType['Sales]', 'Type of solution (check all that apply):', 'Sales', null, Sales);

Now the output is:
[__solutionType] => Array ( [Sales] => 1 ) [solutionType] => Array ( [Sales] => Sales [Marketing] => [Service/Help Desk] => )

Defining it like this, I can use the __solutionType array's keys to tell me the exact text of the elements that the user selected. Note that if this code is used in conjunction with defaults (for instance, if and when I allow the submitter to edit the values, I'd want to load it up with what they originally submitted), I'd probably want to use the solutionType array instead, or pay attention to the values of the __solutionType array to handle the case when the user unchecks an option.

Tags: No Comments

Leave A Comment

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.