多选,设置默认选定值

时间:2009-08-11 08:45:28

标签: zend-framework

如何在控制器中设置多选的选定值? 到目前为止,这是我的代码

    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>

3 个答案:

答案 0 :(得分:21)

您可以将值数组传递给setValue()

数组中的值应与设置multiOptions时传递的键相对应。

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

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

From the ZF manual:

  

要标记选中的项目,您需要   将一组值传递给setValue()。

答案 1 :(得分:2)

我通常在表单上使用setDefaults() - 您也可以在元素上使用setValue(),但是将多选的“选定选项”设置为所选id的数组(就像它返回一个值一样) 。

$categories = // model funciton to get selected categories for this entry.
$selected=array();
foreach ($categories as $category)
{
  $selected[] = $category->ID;
}
$form->setDefaults(array('categories' => $selected));

答案 2 :(得分:0)

如果您更喜欢通过数组传递选项而不是使用离散元素,您也可以这样做:

$this->addElement('select', 'element_name', array(
  'label'=>'Element Label',
  'value'=> array('value_name'=>'Value Label',
  'multiOptions' => array(
      'value_name'=>'Value Label',
      'value_name_2'=>'Value Label 2',
      'value_name_3'=>'Value Label 3',
));

重要的部分是$ options数组的'value'键。

这将导致选择第一个元素。

相关问题