我正在尝试使用Nette\Forms呈现表单,其中字段类型存储在数据库中。因此,取决于该字段是电子邮件还是简单的文本输入;验证类型将有如下不同之处:
$form->addText($field['name'], $field['label'])
->setRequired('Enter your email');
if ($field['type'] == ['email']) {
$form->addRule(FORM::EMAIL, 'Enter a valid email');
}
如果它只是一个字段,我可以使用if条件,但会有更多的字段,这样做似乎不切实际。因为它是一个链式方法,所以我不能通过输入如下的中间if语句来破坏方法:
switch(currentC.data("template")) {
case "cataction1": {
currentC.addClass( "active cataction1Current" );
$( ".catbarlist li" ).not( currentC ).removeClass( "cataction2Current cataction3Current cataction4Current cataction5Current active activenotransit" );
break;
}
case "cataction2": {
currentC.addClass( "active cataction2Current" );
$( ".catbarlist li" ).not( currentC ).removeClass( "cataction1Current cataction3Current cataction4Current cataction5Current active activenotransit" );
break;
}
case "cataction3": {
currentC.addClass( "active cataction3Current" );
$( ".catbarlist li" ).not( currentC ).removeClass( "cataction1Current cataction2Current cataction4Current cataction5Current active activenotransit" );
break;
}
case "cataction4": {
currentC.addClass( "active cataction4Current" );
$( ".catbarlist li" ).not( currentC ).removeClass( "cataction1Current cataction2Current cataction3Current cataction5Current active activenotransit" );
break;
}
case "cataction5": {
currentC.addClass( "active cataction5Current" );
$( ".catbarlist li" ).not( currentC ).removeClass( "cataction1Current cataction2Current cataction3Current cataction4Current active activenotransit" );
break;
}
}
除了为每组规则使用条件语句之外,还有更好的方法吗?
答案 0 :(得分:4)
您在addRule()
对象本身上调用$form
,而不是$form->addText()
调用的返回值。
$name = $form->addText($field['name'], $field['label'])
if ($field['type'] == ['email']) {
$name->setRequired('Enter your email')
->addRule(FORM::EMAIL, 'Enter a valid email');
}