我正在尝试在表单上实现 Zend 2 中的"InArray"验证器,但它一直返回无效。这是代码:
表单元素设置:
$enquiryType = new Element'Select('enquiryType');
$enquiryType->setLabel('* What is your enquiry about?')
->setLabelAttributes(array('class' => 'sq-form-question-title'))
->setAttribute('class', 'sq-form-field required')
->setValueOptions($enquiryTypes);
过滤器/验证器设置:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes));
这是通过 module.config.php 文件传递到$enquiryTypes的数组
'enquiryCategories' => array(
'empty_option' => 'Please select an option',
array(
'label' => 'General enquiries',
'options' => array(
'skype' => 'Skype with your library feedback',
'question' => 'Ask a question',
'feedback' => 'Library feedback',
'eresource' => 'Electronic resources (e.g. e-book, e-journal, database)',
'webbridge' => 'WebBridge Problems',
'dro' => 'DRO'
)
),
array(
'label' => 'Application to review',
'options' => array(
'10400' => 'I''ve returned the item',
'10401' => 'I didn''t know about overdue points but now I have some',
'10402' => 'Why did I get this invoice?',
'10403' => 'The item I borrowed is lost',
'10404' => 'The item I borrowed has been damaged',
'10405' => 'I never got/had the book',
'10406' => 'Other'
)
)
),
我已经尝试了不同的变体(也使用递归验证),但无法解决这个问题。
我会尝试的一件事如下:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes['enquiryCategories']));
我这么说的原因是,看起来您可能正在数组内部创建一个数组。除非我误解了描述。
如果这对您不起作用,那么您可能需要探索以下问题中指出的"分解"选项。
ZF2: 如何使用 InArray 验证器验证多选表单元素?
祝你好运。
我终于得到了一个可行的解决方案。我觉得应该有更好的解决方案,但我找不到。
这是我使用的过滤器:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => array_keys(
$enquiryTypes[0]['options']+$enquiryTypes[1]['options']
)));
$enquiryType->getFilterChain()
->attach(new Filter'StringToLower())
->attachByName('StripTags');
基本上,我必须将数组选项分解为一个直接的关联数组。由于数组在这种情况下保持静态,因此效果很好。
如果数据变得动态,那么还需要更多的东西(遍历并找到"选项"键,将子项添加到过滤器数组等......