ZF2只根据另一个元素创建一个表单元素?

时间:2017-06-15 15:44:08

标签: validation zend-framework2 zend-form2

所以我的表单中有一个元素列表,其中一个是带有简单yes / no选项的选择框。当字段为“no”时,我想使下一个输入字段成为必需。

目前我的输入过滤器如下:

return [
    [
        'name' => 'condition',
        'required' => true,
    ],
    [
        'name' => 'additional',
        'required' => false,
        'validators' => [
            [
                'name' => 'callback',
                'options' => [
                    'callback' => function($value, $context) {
                        //If condition is "NO", mark required
                        if($context['condition'] === '0' && strlen($value) === 0) {
                            return false;
                        }
                        return true;
                    },
                    'messages' => [
                        'callbackValue' => 'Additional details are required',
                    ],
                ],
            ],
            [
                'name' => 'string_length',
                'options' => [
                    'max' => 255,
                    'messages' => [
                        'stringLengthTooLong' => 'The input must be less than or equal to %max% characters long',
                    ],
                ],
            ],
        ],
    ],
];

我发现的是因为'required' => false,字段additionalvalidators字段都没有。

如果additional为“否”(值为“0”),我该如何才能condition?{/ p>

1 个答案:

答案 0 :(得分:1)

可以从getInputFilterSpecification函数中检索元素。因此,可以根据相同表单或字段集中的另一个元素的值将元素标记为required

'required' => $this->get('condition')->getValue() === '0',

有了这个,我也可以摆脱大量的callback验证器。

return [
    [
        'name' => 'condition',
        'required' => true,
    ],
    [
        'name' => 'additional',
        'required' => $this->get('condition')->getValue() === '0',
        'validators' => [
            [
                'name' => 'string_length',
                'options' => [
                    'max' => 255,
                    'messages' => [
                        'stringLengthTooLong' => 'The input must be less than or equal to %max% characters long',
                    ],
                ],
            ],
        ],
    ],
];