HTML_QuickForm – Setting the advcheckbox Checked Value

I must have spent an hour looking for a solution to this problem. Hopefully this post will save someone from the agony I went through. This problem is specific to PEAR HTML_QuickForm, so anyone who doesn't know what that is can enjoy the pretty colors. 🙂

With the standard 'checkbox' element you can simply append the word 'checked' as the last attribute in the addElement method, like this:

$form->addElement('checkbox','remember','Remember me?',
                         '(Check this to remember your login info.)', 'checked');

However, with advcheckbox, which is required if you want to define the checkbox values, setting the checked value from the addElement method is not possible. So how do you do it? First a quick review of the options available with advcheckbox:

  addElement('advcheckbox',
             string element-name,   // name of advcheckbox
             string element-label,  // label output before advcheckbox
             string text,           // label output after advcheckbox
             mixed attributes,      // string or array of attributes
             mixed values);

OK, now here is what I had to do to solve the problem:

$formCheckbox = $form->createElement('advcheckbox',mycheckbox,'',
                                               $row['name'],null,$row['permission_id']);
if(in_array($row['permission_id'], $groups2perms))
	$formCheckbox->setChecked(true); // <-- this is where the magic happens!
else
	$formCheckbox->setChecked(false); // <-- here too!

$form->addElement($formCheckbox);

Thats it! As you can see, you need to use the setChecked() method. However, before you can use it you have to assign the object to a variable ($formCheckbox = $form->createElement(..,..)) and then call the setChecked() method on that variable ($formCheckbox->setChecked(true)). Keep in mind that you can call any number of available methods on the variable before using the addElement() method.

Write a Comment

Comment

  1. On form – 10
    On color – 4; it was like looking at a cga monitor
    On magic – 5; Where’s the rabbit jumping out of the hat?

    I don’t do much with forms yet, and I’m glad I don’t – their confusing to me, but maybe someday this post will be like GOLD to me.

  2. Thanks for taking the time to post this. I’m at the end of a 4 hour search now. I swear, pear documentation really sucks.

  3. I know your pain very well. I too have spent countless hours searching for PEAR specific things, especially with relation to HTML_QuickForm!

  4. Thanks for the info.

    How do we use advcheckbox to have an array of checkboxes though, like:

    ?

    I hate PEAR QuickForms!

  5. Like this:

    < input type=”checkbox” name=”options[]” value=”option1″ />
    < input type=”checkbox” name=”options[]” value=”option2″ />
    < input type=”checkbox” name=”options[]” value=”option3″ />