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>
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With