zend-frameworkzend-form

Zend Form - setting defaults for multi checkbox


The HTML for my checkbox list is like this:

<dt id="list-label">
    <label for="list" class="optional">
        Choose which feeds to include in the mix
    </label>
</dt>

<dd id="list-element">
    <label for="list-1">
        <input type="checkbox" name="list[]" id="list-1" value="1">Marko Polo
    </label>

    <br />

    <label for="list-2">
        <input type="checkbox" name="list[]" id="list-2" value="2">Jeano Polo
    </label>
</dd>

I'm trying to pre-populate them with selected=selected for those with values of 1 from the database. I thought the following would work:

$form->setDefaults(array('list-1'=>1,'list-2'=>1));

But it doesn't. Is there a way to do this?

EDIT

Here is my form class code:

            $model = new Admin_Model_Db();
            $model->setTableName('graduates');
            $gradA = $model->getAllGraduates();

            foreach ($gradA as $grad){
                if (!empty($grad['twitter'])){
                    $twitter[$grad['id']] = $grad['firstname'] . ' ' . $grad['lastname'];
                }
            }

            $list = $this->CreateElement('multicheckbox', 'list')
                                  ->setLabel('Choose which feeds to include in the mix')
                                  ->setRequired(false)
                                  ->setMultiOptions($twitter);

Solution

  • Your form element name is list[], this means that when your boxes are checked and you get their values this way :

     $list = $form->getElement('list')->getValue();
    

    $list's value will be array(1,2)

    So logically this should work :

    $form->setDefaults(array('list'=>array(1,2));
    //if not, try with strings instead of integers array('1','2')