当必须设置多个输入项中的一个时,如何在Zend Framework 2应用程序中处理案例


How to handle a case in a Zend Framework 2 application, when one of multiple input items must be set?

我目前正在开发的ZF2应用程序是Apigility驱动的,但我必须将一些InputFilter设置从module.config.php移动到单独的InputFilter文件/类。

现在我有字段CompanyIdUserId。必须设置其中一个(也是唯一一个)。我已经用Callback验证器进行了尝试,请参阅下文。但它不起作用:如果两个字段都缺失,则不会执行验证。

如何解决这个问题?

class AddressPostRequestInput implements ArraySerializableInterface {
    ...
    public function __construct() {
        $this->dataSet = [
            'CompanyId' => null,
            'UserId'    => null,
            'Type'      => null,
        ];
    }
    ...
    public function getInputFilter() {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory     = new InputFactory();
            ...
            $inputFilter->add($factory->createInput(array(
            ...
            $inputFilter->add($factory->createInput(array(
            'name' => 'CompanyId',
            'required' => false,
            'filters' => array(
                ...
            ),
            'validators' => array(
                array(
                    'name' => 'Callback',
                    'options' => array(
                    'callback' => function ($value, $context = array()) {
                        $isValid =
                            (isset($context['UserId']) && !isset($context['CompanyId'])) ||
                            (!isset($context['UserId']) && isset($context['CompanyId']))
                        ;
                        return $isValid;
                    },
                ),
            ),
            $inputFilter->add($factory->createInput(array(
            'name' => 'UserId',
            'required' => false,
            'filters' => array(
                ...
            ),
            'validators' => array(
                array(
                    'name' => 'Callback',
                    'options' => array(
                    'callback' => function ($value, $context = array()) {
                        $isValid =
                            (isset($context['UserId']) && !isset($context['CompanyId'])) ||
                            (!isset($context['UserId']) && isset($context['CompanyId']))
                        ;
                        return $isValid;
                    },
                ),
            ),
        )));
        $this->inputFilter = $inputFilter;
    }
    ...
}

我永远记不清这些设置需要什么组合,但它会像:

    $inputFilter->add($factory->createInput(array(
        'name' => 'CompanyId',
        'required' => false,
        'allow_empty' => true,
        'continue_if_empty' => true,
        'filters' => array(
            ...
        ),

可能需要稍微调整一下,但应该可以使用

continue_if_empty和allow_empty设置以及已实现的回调验证器