Zend表格无线电默认检查

时间:2010-09-07 14:33:56

标签: php zend-framework radio-button zend-form

我有下一个单选按钮组:

$enabled = $this->createElement('radio', 'enabled')
                ->setLabel('Enabled')
                ->setMultiOptions(array('1'=>'yes', '0'=>'no'))
                ->setValue($rank_values['enabled'])
                ->setAttrib('id', 'enabled')
                ->setAttrib('class', $action . '_enabled')
                ->setSeparator('');

如何设置已检查的收音机?现在,当我打开我的脚本时,没有选择收音机。我想选择'是'。怎么样?

谢谢。

5 个答案:

答案 0 :(得分:7)

它更容易:)

$enabled = $this->createElement('radio', 'enabled')
                ->setLabel('Enabled')
                ->setMultiOptions(array('1'=>'yes', '0'=>'no'))
                ->setValue($rank_values['enabled'])
                ->setAttrib('id', 'enabled')
                ->setAttrib('class', $action . '_enabled')
                ->setSeparator('')
                ->setValue("1");

答案 1 :(得分:7)

如果有人想知道,我使用数组表示法在我的表单和zend框架2中声明我的所有元素以在单选按钮中选择默认选项,你必须添加属性值并使其成为拥有默认情况下要选择的value_options的键:

// Inside your constructor or init method for your form //
$this->add(
        [
            'type'       => 'Radio',
            'name'       => 'some_radio',
            'options'    => [
                'value_options' => [
                    'opt1' => 'Radio option 1',
                    'opt2' => 'Radio option 2'
                ]
            ],
            'attributes' => [
                'value' => 'opt1' // This set the opt 1 as selected when form is rendered
            ]
        ]
    );

我发现一些例子有点令人困惑,因为他们在值选项(0,1)中使用了数字键,所以当我看到' value' => 1对于我来说,这对于value_options数组中的关键并不明显。希望这有助于某人。

答案 2 :(得分:3)

使用此:

->setAttrib("checked","checked")

这样你的完整代码就像这样:

$enabled = $this->createElement('radio', 'enabled')
            ->setLabel('Enabled')
            ->setMultiOptions(array('0'=>'no', '1'=>'yes'))
            ->setAttrib("checked","checked")
            ->setValue($rank_values['enabled'])
            ->setAttrib('id', 'enabled')
            ->setAttrib('class', $action . '_enabled')
            ->setSeparator('');

[编辑] 使用setValue

您也可以使用它:

->setValue('1')

这将检查由值1表示的选项yes

答案 3 :(得分:1)

我发现如果你有一个过滤器集,那么->setvalue('X')就不起作用了。

我删除了->addFilter('StringToLower')
并添加了->setSeparator('')->setValue('N');

进行了一次治疗

答案 4 :(得分:0)

呀。我已经使用jQuery解决了它:

jQuery(document).ready(function(){
    var $radios = $('input:radio[name=enabled]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=1]').attr('checked', true);
    }
});
相关问题