【问题标题】:How to get the selected option of a radion button element in Zend Framework 2?如何在 Zend Framework 2 中获取单选按钮元素的选定选项?
【发布时间】:2016-11-09 11:57:37
【问题描述】:

Fieldset 中,我有一个Element\Radio fooElement\Text bar

public function init()
{
    $this->add(
        [
            'type' => 'radio',
            'name' => 'foo',
            'options' => [
                'label' => _('foo'),
                'value_options' => [
                    [
                        'value' => 'a',
                        'label' => 'a',
                        'selected' => true
                    ],
                    [
                        'value' => 'b',
                        'label' => 'b'
                    ]
                ]
            ]
            ...
        ]);

    $this->add(
        [
            'name' => 'bar',
            'type' => 'text',
            'options' => [
                'label' => 'bar',
                ...
            ],
            ...
        ]);
}

bar 字段的验证取决于所选的foo 选项。很容易实现,如果我能得到foo的选定值:

public function getInputFilterSpecification()
{
    return [
        'bar' => [
            'required' => $this->get('foo')->getCheckedValue() === 'a',
            ...
        ],
    ];
}

但是没有方法Radio#getCheckedValue()。好吧,我可以遍历$this->get('foo')->getOptions()['value_options'],但这真的是唯一的方法吗?

如何获得(在Fieldset#getInputFilterSpecification() 中)Zend\Form\Element\Radio 的选定选项?

【问题讨论】:

    标签: zend-framework2 radio-button zend-form zend-form-element zend-form-fieldset


    【解决方案1】:

    选定的选项与 HTML 表单中的所有其他内容一起被 POST 到服务器,并且所有这些都可以通过 $context 数组在验证器中使用。 您可以使用回调验证器和$context 数组来创建有条件的必填字段,如下所示:

    public function getInputFilterSpecification() {
        return [
            'bar' => [
                'required' => false,
                'allow_empty' => true,
                'continue_if_empty' => true,
                'required' => true,
                'validators' => [
                    [
                        'name' => 'Callback',
                        'options' => [
                            'callback' => function ($value, $context) {
                                return $context['foo'] === 'a'
                            },
                            'messages' => [
                                \Zend\Validator\Callback::INVALID_VALUE => 'This value is required when selecting "a".'
                            ]
                        ]
                    ]
                ]
            ],
        ];
    }
    

    这将检查'foo'是否等于'a',即选项'a'被选中并返回true,表示输入有效,false,否则表示输入无效。

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 2013-04-03
      • 1970-01-01
      • 2011-07-28
      • 2012-01-05
      • 2013-07-08
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多