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


Zend Framework 2: Set options as "selected" in select list

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

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

我在这里举一个简单的例子,希望它能对您有所帮助。正如您所提到的,要获得所选元素,只需使用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'
        )
    ));

您可以更喜欢此链接了解更多信息如果你得到

干草堆选项是强制性

然后将disable_inarray_validator添加到选项中:

    $this->add(array(
    ...
    'options' => array(
      'disable_inarray_validator' => true,
      'label' => 'county',
    ),
 ));

如果我没有弄错,该值是选项的一部分,而不是属性。

$this->add(array(
    'type' => 'Zend'Form'Element'Select',
    'name' => 'manufacturer',
    'options' => array(
        'label' => 'Manufacturer name',
        'value_options' => $this->getManufacturer(),
        'empty_option'  => '--- select manufacturer ---',
        'value' => '2'
    )
));