views:

1185

answers:

2

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>
+2  A: 

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().

Aron Rotteveel
Sorry, I do not know if my post is unclear or if you just misunderstood the post. But I want to set some of the options as selected. For example if we use your code. I want Foo and Bar to be selected, and Baz and Bat to unselected.
unkown
This is exactly what the above code does.
Aron Rotteveel
Thank you I read you post to fast, I missed the last line :)
unkown
No problem, you're welcome :)
Aron Rotteveel
A: 

I usually use setDefaults() on the form - you can also use setValue() on the element, but you set a multi-select's "selected options" as an array of selected id's (just like it returns for a value).

$categories = // model funciton to get selected categories for this entry.
$selected=array();
foreach ($categories as $category)
{
  $selected[] = $category->ID;
}
$form->setDefaults(array('categories' => $selected));
gnarf
Thank you for you answer but Arons answer is much more beautiful
unkown
I'm still wondering why the downvote... $form->setDefaults() is worth a mention - it will let you set multiple form values at a time as well.
gnarf
I did not down vote you so I do not know. What is all this voting for anyway?
unkown
http://stackoverflow.com/faq#reputation - Welcome to SO!
gnarf