经典问题:
验证用户是否接受了合同条款,但接受的价值未存储(绑定)在数据库中......
- 扩展 CFormModel 而不是 CActiveForm(因为 CActiveForm 将值绑定到 DB)
- 将 CFormModel 发布到控制器操作
- 验证 CFormModel
我要求这个问题来回答它,因为现有问题以查看文档结尾......
经典问题:
验证用户是否接受了合同条款,但接受的价值未存储(绑定)在数据库中......
我要求这个问题来回答它,因为现有问题以查看文档结尾......
扩展 CFormModle,定义规则并进行验证。使用您在保存过程中验证的绑定变量。现在您 validate() 自己但 Validate 需要一个未在 CFormModel 中定义的属性列表。所以你会怎么做?你来做这件事:
$contract->validate($contract->attributeNames())
这是完整的示例:
class Contract extends CFormModel
{
...
public $agree = false;
...
public function rules()
{
return array(
array('agree', 'required', 'requiredValue' => 1, 'message' => 'You must accept term to use our service'),
);
}
public function attributeLabels()
{
return array(
'agree'=>' I accept the contract terms'
);
}
}
然后在控制器中执行以下操作:
public function actionAgree(){
$contract = new Contract;
if(isset($_POST['Contract'])){
//$contract->attributes=$_POST['Contract']; //contract attributes not defined in CFormModel
...
$contract->agree = $_POST['Contract']['agree'];
...
}
if(!$contract->validate($contract->attributeNames())){
//re-render the form here and it will show up with validation errors marked!
}
结果: