【问题标题】:ZF2: How do I use InArray validator to validate Multiselect form element?ZF2:如何使用 InArray 验证器来验证多选表单元素?
【发布时间】:2014-07-17 13:50:09
【问题描述】:

我有一个 ZF2 表单,出于特定原因,我不得不禁用原生验证器。

然后,当以编程方式向表单添加元素时,我还会添加验证器。

其中一个元素是多选数组。

$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 验证器:

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 会做诀窍,但在编写我自己的验证器之前,我确实有一种感觉,这个轮子已经被发明了!

环顾四周,我发现有一个导致此效果的错误 (http://framework.zend.com/issues/browse/ZF2-413),解决方案是引入 Explode 验证器,但我不确定如何将其添加到我的输入过滤器中。

感谢您的建议。

【问题讨论】:

    标签: php validation zend-framework2


    【解决方案1】:

    实际上,按照错误修复链接,我想出了如何进行验证。 Explode 验证器将分解该值并将验证器应用于每个部分:

    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',
                                ),
                            ))
                    )
                ),
            ),
        )));
    }
    

    在这里留下这个问题,因为我自己还没有找到任何其他答案,希望这对未来的人们有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多