ZF2:如何使用 InArray 验证器来验证多选表单元素? [英] ZF2: How do I use InArray validator to validate Multiselect form element?
问题描述
我有一个 ZF2 表单,出于特定原因,我不得不在其中禁用本机验证器.
I have a ZF2 form where I had to disable native validators, for a specific reason.
然后,当以编程方式向表单添加元素时,我也会添加验证器.
Then, when adding elements programatically to the form I also add validators.
其中一个元素是多选数组.
One of the elements is a Multiselect array.
$form->add( array(
'type' => 'Zend\Form\Element\Select',
'options' => array(
(
'label' => 'few items',
'value_options' => Array
(
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four',
)
),
'attributes' => array
(
'multiple' => 'multiple',
'value' => array('two','three'),
'required' => 1,
'id' => 'few_items'
),
'name' => 'few_items'
));
另外,我将添加一个 InArray 验证器:
Also, I'm going to add an InArray validator:
if($f instanceof \Zend\Form\Element\Select){
$inputFilter->add($factory->createInput(array(
'name' => $f->getName(),
'required' => $f->getAttribute('required') == 1,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => $f->getValueOptions(),
'messages' => array(
InArray::NOT_IN_ARRAY => 'Please select an option',
),
),
),
),
)));
}
问题是验证器总是失败,因为在 POST 多选字段中将返回一个数组,实际上查看 InArray 验证器内部,它使用了不适合此的 in_array(...) PHP 函数 - array_intersect 会做诀窍,但在编写我自己的验证器之前,我确实觉得这个轮子已经被发明了!
The problem is that the validator always fails, because in POST multiselect field will return an array, and actually looking inside the InArray validator, it uses in_array(...) PHP function which is not suitable for this - array_intersect would do the trick, but before writing my own validator I do have a feeling that this wheel was invented already!
环顾四周后,我发现有一个错误引起了这种效果 (http://framework.zend.com/issues/browse/ZF2-413),解决方案是引入 Explode 验证器,但我不确定如何将其添加到我的输入过滤器中.
Having looked around I see that there was a bug raised to this effect (http://framework.zend.com/issues/browse/ZF2-413), and the solution was to introduce Explode validator, but I'm not sure how to add it into my input filter.
感谢您的建议.
推荐答案
实际上,按照错误修复链接,我想出了如何进行验证.Explode 验证器将分解该值并将验证器应用于每个部分:
Actually, following the bugfix link, I figured out how to do the validation. Explode validator would break down the value and apply a validator to each part:
if($f instanceof \Zend\Form\Element\Select){
$inputFilter->add($factory->createInput(array(
'name' => $f->getName(),
'required' => $f->getAttribute('required') == 1,
'validators' => array(
array(
'name' => 'Explode',
'options' => array(
'validator' => new InArray(array(
'haystack' => $f->getValueOptions(),
'valueDelimeter' => null,
'messages' => array(
InArray::NOT_IN_ARRAY => 'Please select an option',
),
))
)
),
),
)));
}
把这个问题留在这里,因为我自己还没有找到任何其他的答案,希望这会在未来对人们有所帮助.
Leaving this question here, because I haven't found any other answers to this myself and hopefully this will assist people in the future.
这篇关于ZF2:如何使用 InArray 验证器来验证多选表单元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!