Zend Framework 2:在选择列表中将选项设置为“已选择”

Bla*_*agi 3 php zend-framework2

我正在尝试将第二个产品设置为在列表中选择,但下面的代码不起作用。任何的想法。谢谢

$this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'manufacturer',
        'options' => array(
            'label' => 'Manufacturer name',
            'value_options' => $this->getManufacturer(),
            'empty_option'  => '--- select manufacturer ---',
        ),
        'attributes' => array(
            'value' => 2,
            'selected' => true,
        ),
    ));
Run Code Online (Sandbox Code Playgroud)

Jan*_*thy 5

我这里举一个简单的例子,希望对你有帮助。正如您提到的获取选定元素,简单使用 value 属性具有该选定元素的值,例如:

    $this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'gender',
        'options' => array(
            'label' => 'Gender',
            'value_options' => array(
                '1' => 'Select your gender',
                '2' => 'Female',
                '3' => 'Male'
            ),
        ),
        'attributes' => array(
            'value' => '1' //set selected to '1'
        )
    ));
Run Code Online (Sandbox Code Playgroud)

你可以更喜欢这个链接更多 如果你得到

haystack 选项是强制性的

然后将 disable_inarray_validator 添加到选项中:

    $this->add(array(
    ...
    'options' => array(
      'disable_inarray_validator' => true,
      'label' => 'county',
    ),
 ));
Run Code Online (Sandbox Code Playgroud)