Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiselect, set default selected values

How can I set selected values for a multiselect within my controller? This is my code so far

    class Blog_Form_Post extends Zend_Form
    {
        public function init()
        {
    ...
            $this->addElement('multiselect', 'categories', array(
                'label'      => 'Categories:',
                'required'   => false,
            )); 
    ...

            $form = new Blog_Form_Post();
            $categories = new Blog_Model_DbTable_Categories();
            $categories = $categories->fetchAll();
            foreach ($categories as $category)
            {
// Some of the categories needs to selected by default
                $form->getElement('categories')->addMultiOption($category->ID, $category->name);


        } 

Edit to be more clear. I am taking the example from Aron Rotteveel

$multi->setMultiOptions(array(
    'foo' => 'Foo',
    'bar' => 'Bar',
    'baz' => 'Baz',
    'bat' => 'Bat',
));

I want Foo and Bar to be selected while Baz and Bat should be unselected when the form is rendered. IE

<select name="categories[]" id="categories" multiple="multiple">
    <option selected="selected" value="foo">foo</option>
    <option selected="selected"value="bar">bar</option>
    <option value="baz">baz</option>
    <option value="bat">bat</option>
</select>
like image 574
unkownt Avatar asked Aug 11 '09 08:08

unkownt


1 Answers

You can pass an array of values to setValue().

The values in the array should correspond to the keys passed when setting the multiOptions.

$multi->setMultiOptions(array(
    'foo' => 'Foo',
    'bar' => 'Bar',
    'baz' => 'Baz',
    'bat' => 'Bat',
));

$multi->setValue(array('foo', 'bar')); 

From the ZF manual:

To mark checked items, you need to pass an array of values to setValue().

like image 194
Aron Rotteveel Avatar answered Oct 16 '22 17:10

Aron Rotteveel