zend-framework – multiselect,设置默认选择的值

如何在控制器内设置多重选择的选择值?
这是我的代码到目前为止

    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);


        } 

编辑更清晰.我以Aron Rotteveel为例

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

我想要Foo和Bar被选中,而Baz和Bat应该在渲染表单时被取消选择. 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>
最佳答案
您可以将值数组传递给setValue().

数组中的值应与设置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().

转载注明原文:zend-framework – multiselect,设置默认选择的值 - 代码日志