如何获取Zend Framework 2中的Radion按钮元素的选定选项?
问题描述:
在Fieldset
我有一个Element\Radio
foo
和Element\Text
bar
。如何获取Zend Framework 2中的Radion按钮元素的选定选项?
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
的选定选项?
答
所选择的选项被发送到服务器与一切从HTML表单一起,是这一切是通过$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".'
]
]
]
]
],
];
}
这将检查,如果“富”等于“一”,即选择“A”选择和回报: 您可以通过使用回调验证和$context
阵列像这样创建一个条件必需的场true
它是什么时候,它将输入标记为有效,当它不是时,标记输入无效。