1

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

目前我的输入过滤器看起来像:

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,这个additional领域,没有validators跑步。

additional仅当condition“否”(值“0”)时,我如何才需要?

4

1 回答 1

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',
                    ],
                ],
            ],
        ],
    ],
];
于 2017-06-15T15:44:08.457 回答