ZF2 仅根据另一个元素制作一个必需的表单元素?

ZF2 Only make a form element required based on another element?

所以我的表单中有一个元素列表,其中一个是带有简单 yes/no 选项的 select 框。当字段为 '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',
                    ],
                ],
            ],
        ],
    ],
];

我发现的是因为 additional 字段有 'required' => false,validators 运行 字段有 none。

如何让 additional 仅在 condition 为 'no'(值“0”)时才需要?

可以从 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',
                    ],
                ],
            ],
        ],
    ],
];