我的表单中有2个文本字段。
用户提交表单后, 如果TextFielA的值不为空,如何将Validator / setRequired(true)添加到TextFieldB?
答案 0 :(得分:2)
除了@ Marcin的想法,我还有两种方法。
通过在表单上创建setRequired()
方法并在控制器中调用它,有条件地调用相关元素上的preValidate()
。 [与@Marcin真的相同,但是将其推入表格本身,让控制器更加精简。]
创建一个名为ConditionallyRequired
的自定义验证程序,它接受“其他字段”的字段名作为选项。然后将此验证器附加到每个元素,并使用“other”元素的名称对其进行配置。然后在验证程序的isValid($value, $context)
方法中,如果$value
非空,则有条件地测试$context['otherfield']
。
答案 1 :(得分:1)
你可以这样做:
if ($this->getRequest()->isPost()) {
$textFieldA = $yourForm->getElement('TextFieldA');
$textFieldB = $yourForm->getElement('TextFieldB');
if (!empty($_POST['TextFieldA'])) {
$textFieldB->setRequired(true);
}
if (!empty($_POST['TextFieldB'])) {
$textFieldA->setRequired(true);
}
if ($mainForm->isValid($_POST)) {
// process the form
}
}
基本上,您在发布后添加验证器,但在验证表单之前。 希望这会有所帮助。